Can somebody explain this odd behavior when working with ThreadPool?

后端 未结 2 1512
南方客
南方客 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:46

    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);
    
    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题