wtorek, 24 lutego 2009

lambdas + threading = problem

Lambdas introduced in C# 3.0 are great, but sometimes it might be tempting to use them to fit prototype of method invoked in thread to Thread class constructor argument e.g.:

static void f(int i)
{
Console.WriteLine(i);
}

static void Main(string[] args)
{
for (int i = 0; i < 10; ++i)
{
new Thread(() => f(i)).Start();
}
...
}

Interesting results - isn't it? No copy - no good!
For one argument it can be written

static void f(int i)
{
Console.WriteLine(i);
}

static void Main(string[] args)
{
for (int i = 0; i < 10; ++i)
{
new Thread(a => f((int)a)).Start(i);
}
...
}

Brak komentarzy:

Prześlij komentarz