繁体   English   中英

有人可以解释使用 ThreadPool 时这种奇怪的行为吗?

[英]Can somebody explain this odd behavior when working with ThreadPool?

编码

using System;
using System.Threading;

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

public static class Program
{
    public static void Main(string[] args)
    {
        LoadTest loadTest = new LoadTest();
        loadTest.LoadItems(args);
    }
}

public class LoadTest
{       
    ManualResetEvent resetEvent;
    int numThreads = 0;

    public LoadTest()
    {}

    public void LoadItems(string[] Items)
    {
        numThreads = 0;
        resetEvent = new ManualResetEvent(false);

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

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

        }
        resetEvent.WaitOne();
    }

    public void progCall(double PercentComplete, string ItemName)
    {
        Console.WriteLine("{0}: is {1}% Complete [THREAD:{2}]",ItemName,PercentComplete.ToString(),Thread.CurrentThread.ManagedThreadId.ToString());
    }
    public void compCall(int ItemID, string ItemName)
    {
        Console.WriteLine("{0}: is Complete",ItemName);
        numThreads--;
        if(numThreads == 0)
        {
            resetEvent.Set();
        }
    }

    public void Load(string Item, LoadingProgressCallback progressCallback, LoadCompleteCallback completeCallback)
    {
        Console.WriteLine("Loading: {0} [THREAD:{1}]",Item,Thread.CurrentThread.ManagedThreadId.ToString());

        for(int i = 0; i <= 100; i++)
        {
            if(progressCallback != null)
            {
                progressCallback((double)i, Item);
            }
            Thread.Sleep(100);
        }
        if(completeCallback != null)
        {
            completeCallback(0,Item);
        }
    }
}

观察

如果我从命令行运行这个程序,就像这样......

>TheProgram item1 item2

输出将如下所示。

将 item1 添加到线程池
正在加载:item1 [线程:3]
item1:完成 0% [线程:3]
将 item2 添加到线程池
正在加载:item2 [线程:4]
item2:完成 0% [线程:4]
item1:完成 1% [线程:3]
item2:完成 1% [线程:4]
item1:完成 2% [线程:3]
item2:完成 2% [线程:4]

但是,如果我删除此行。

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

LoadItems方法的输出如下所示。

将 item1 添加到线程池
将 item2 添加到线程池
正在加载:item2 [线程:4]
正在加载:item2 [线程:3]
item2:完成 0% [线程:4]
item2:完成 0% [线程:3]
item2:完成 1% [线程:4]
item2:完成 1% [线程:3]
item2:完成 2% [线程:3]
item2:完成 2% [线程:4]

问题

似乎正在使用两个线程,尽管它们似乎都在处理相同的数据。 为什么代码会这样?

您正在关闭循环变量,这会给您带来意想不到的结果。 试试这个:

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

}

参考

查看代码时立即想到的一件事是缺乏Interlocked的使用。

你必须使用它,否则你会看到奇怪的错误和行为。

所以代替

numThreads++;

用:

Interlocked.Increment(ref numThreads);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM