Tuesday, January 26, 2016

Anonymous method with Parameters 'i' -> Thread -> Iteration with 'i' -> Mess!

Problem:
You see IndexOutOfRangeException with message  "Index was outside the bounds of the array." when you thread out an anonymous method with iterator value as parameter.


Cause:
Surprised? How is it possible to see value i >= 4 (it was 4) in the 'for' loop there?
Well, it's 'possible' if your have written code as above.

Secret is that the anonymous method doesn't get called unless the Thread created doesn't becomes live. Once thread becomes live, it searches for it's anonymous method which is: MethodToCompute(NumberOfIterationPerThread[i])
Here, value of 'i' might have changed as 'for' loop to create thread runs in a different thread!

Solution:
solution is NOT to pass any value to threaded anonymous method which the parent thread may modify. In above case, I would create an extra variable to store value to pass to anonymous method which will be threaded out.

    for (int i = 0; i < NumberOfThreads; i++)
    {
        int iterationToRun = NumberOfIterationPerThread[i]; //magic line!
        threads[i] = new Thread(new ThreadStart(() => MethodToCompute(iterationToRun)));
        threads[i].IsBackground = true;
        threads[i].Start();
    }

No comments: