Lets say I have:

private void MyMethod()
{
    for (int a = 0; a < 10; a++)
    {
        for (int b = 0; b < 10; b++)
        {
            Thread thread = new Thread(() => MyThread(a, b));
            thread.Start();
        }
    }
}
private void MyThread(int a, int b)
{
    MoreMethods(a, b);
}

How can I make this thread safe, ie, ensure that each parameter in MyThread method, and all subsequent method calls, remains the value of which it was called with?

1 Answers

3
Henk Holterman On

Your problem is that a and b are captured by the lambda.

Just make copies:

for (int a = 0; a < 10; a++)
{
    for (int b = 0; b < 10; b++)
    {
        int a2 = a, b2 = b;
        Thread thread = new Thread(() => MyThread(a2, b2));
        thread.Start();
    }
}

Now a2 and b2 are captured but they have local scope.