I'm trying to implement Tasks im my Application. Here's a sample code:
There's one simple Interface I, 3 classes are derived form it (A,B,C) I create a list of Is, poplualte it with A, B, C instances, and then create a tasf for each other to call method do1();
interface I
{
void do1();
}
class A : I
{
public void do1()
{
Console.WriteLine("A");
}
}
class B : I
{
public void do1()
{
Console.WriteLine("B");
}
}
class C : I
{
public void do1()
{
Console.WriteLine("C");
}
}
class Program
{
public static void Main(string[] args)
{
List<I> l = new List<I>();
l.Add(new A());
l.Add(new B());
l.Add(new C());
var TaskPool = new List<Task>();
foreach (var i in l)
{
Task task = new Task( () => i.do1()
);
TaskPool.Add(task);
}
foreach (var c in TaskPool)
{
c.Start();
}
Thread.Sleep(3000);
Console.Read();
}
}
I'm expecting to see
A
B
C
in output, but instead of it i get
C
C
C
I kinda found the problem in debugger: all tasks have the same delegate, but i do not know why and how to workaround this. Any Ideas?
Thanks, Ilya.