Hello,
I want to create an object which can be parametrized by any function, and can run this function in another thread, like:
AsyncCalculation<int> = new AsyncCalculation<int>( ..here is a function ..);
I cannot use specific delegate because it is up do developer to decide which function with which parameters he/she wants to use. So I decided to use my own invoker which can return a result.
Here is a code:
public delegate T Invoker<T>(); static void Main(string[] args) { List<Invoker<int>> list = new List<Invoker<int>>();
for (int j = 0; j < 10; j++) { Invoker<int>inv2 = new Invoker<int>( delegate() { Thread.Sleep(100); //do something in the thread Console.WriteLine(j); return j; });
//here I want to pass my inv2 variable as a parameter //into another function to run it in another thread, //but just store it in the collection list.Add(inv2); }
foreach (Invoker<int> inv in list) inv();
Console.ReadKey(); }
As you see, I want to have a list of Invokers to start them later in different threads.
But the output of this program is:
10 10 10 10 ......
As I understand, it is because my anonymous delegate is compiled as a class, and the variable "j" becomes a field of this class. And all the Invokers have the reference to the same instance of this class.
So, my question is: - Is it possible to have MethodInvokers with different instances in them How to create these instances if I only have delegates
- Could you offer another solution of my problem
.NET Development22
|