我正在尝试执行以下代码。该代码尝试并行下载和保存图像。我传递了要下载的图像列表。我用 C# 3.0 编写了此代码,并使用 .NET Framework 4(VS.NET Express 版本)对其进行了编译。 WaitAll 操作会导致NotSupportedException(不支持 STA 线程上多个句柄的 WaitAlll)每次我尝试运行我的程序时。我尝试删除SetMaxThreads
,但这没有任何区别。
public static void SpawnThreads(List<string> imageList){
imageList = new List<string>(imageList);
ManualResetEvent[] doneEvents = new ManualResetEvent[imageList.Count];
PicDownloader[] picDownloaders = new PicDownloader[imageList.Count];
ThreadPool.SetMaxThreads(MaxThreadCount, MaxThreadCount);
for (int i = 0; i < imageList.Count; i++) {
doneEvents[i] = new ManualResetEvent(false);
PicDownloader p = new PicDownloader(imageList[i], doneEvents[i]);
picDownloaders[i] = p;
ThreadPool.QueueUserWorkItem(p.DoAction);
}
// The following line is resulting in "NotSupportedException"
WaitHandle.WaitAll(doneEvents);
Console.WriteLine("All pics downloaded");
}
您能让我了解我遇到的问题是什么吗?
谢谢
我建议不要使用多个WaitHandle
等待完成的实例。使用倒计时活动类代替。它会产生更优雅和可扩展的代码。另外,WaitHandle.WaitAll
方法仅支持最多 64 个句柄,并且不能在 STA 线程上调用。通过重构代码以使用规范模式,我想出了这个。
public static void SpawnThreads(List<string> imageList)
{
imageList = new List<string>(imageList);
var finished = new CountdownEvent(1);
var picDownloaders = new PicDownloader[imageList.Count];
ThreadPool.SetMaxThreads(MaxThreadCount, MaxThreadCount);
for (int i = 0; i < imageList.Count; i++)
{
finished.AddCount();
PicDownloader p = new PicDownloader(imageList[i]);
picDownloaders[i] = p;
ThreadPool.QueueUserWorkItem(
(state) =>
{
try
{
p.DoAction
}
finally
{
finished.Signal();
}
});
}
finished.Signal();
finished.Wait();
Console.WriteLine("All pics downloaded");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)