ThreadPool behaves differently for debug mode and runtime

I want to use ThreadPool to complete lengthy tasks in less time. My methods of course, of course, but I prepared a simple example so that you understand my situation. If I run this application, it will throw an ArgumentOutOfRangeException in the commented line. It also shows that I am 10. How can it go into a for loop if it is 10?

If I do not start the application and do not debug this code, it does not throw an exception and works fine.

public void Test()
{
    List<int> list1 = new List<int>();
    List<int> list2 = new List<int>();

    for (int i = 0; i < 10; i++) list1.Add(i);
    for (int i = 0; i < 10; i++) list2.Add(i);

    int toProcess = list1.Count;

    using (ManualResetEvent resetEvent = new ManualResetEvent(false))
    {
        for (int i = 0; i < list1.Count; i++)
        {
            ThreadPool.QueueUserWorkItem(
                new WaitCallback(delegate(object state)
                {
                    // ArgumentOutOfRangeException with i=10
                    Sum(list1[i], list2[i]);

                    if (Interlocked.Decrement(ref toProcess) == 0)
                        resetEvent.Set();

                }), null);
        }

        resetEvent.WaitOne();
    }

    MessageBox.Show("Done");
}

private void Sum(int p, int p2)
{
    int sum = p + p2;
}

What is the problem?

+4
source share
2 answers

The problem is that i==10, but your lists contain 10 items (i.e. the maximum index is 9).

, , . , ? .

, i 0-9. , , i 10. i, i , .

:

for (int i = 0; i < list1.Count; i++)
{
    var idx=i;
    ThreadPool.QueueUserWorkItem(
        new WaitCallback(delegate(object state)
        {
            // ArgumentOutOfRangeException with i=10
            Sum(list1[idx], list2[idx]);

            if (Interlocked.Decrement(ref toProcess) == 0)
                resetEvent.Set();

        }), null);
}

"private" i , .

-. .

+3

?

Closure. i, , .

for:

var currentIndex = i:
Sum(list1[currentIndex], list2[currentIndex]);
+2

Source: https://habr.com/ru/post/1584258/


All Articles