Can somebody explain this odd behavior when working with ThreadPool?

若如初见. 提交于 2019-11-27 16:13:52
Mark Byers

You're closing over the loop variable, which gives you an unexpected result. Try this instead:

foreach(string item in Items)
{
    string item2 = item;
    Console.WriteLine("Adding {0} to ThreadPool", item2);
    ThreadPool.QueueUserWorkItem
    (
        delegate
        {
            Load(item2, this.progCall, this.compCall);
        }
    );
    numThreads++;

    Thread.Sleep(100);//Remove this line

}

References

One thing that immediately comes to mind looking at the code is lack of use of Interlocked.

You have to use it otherwise you will see strange errors and behaviours.

So instead of

numThreads++;

Use:

Interlocked.Increment(ref numThreads);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!