Can somebody explain this odd behavior when working with ThreadPool?

后端 未结 2 1523
南方客
南方客 2020-12-04 02:17

The Code

using System;
using System.Threading;

public delegate void LoadingProgressCallback(double PercentComplete,string ItemName);
public delegate void          


        
2条回答
  •  独厮守ぢ
    2020-12-04 02:59

    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

    • Closing over the Loop Variable in C#
    • Closing over the loop variable considered harmful

提交回复
热议问题