我正在尝试执行以下代码。代码试图以并行方式下载和保存图像。我传递要下载的图像列表。我用C# 3.0编写了这篇文章,并使用.NET Framework4 (VS.NET速成版)编译了它。每次尝试运行程序时,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");
}你能让我明白我遇到了什么问题吗?
谢谢
发布于 2010-09-24 05:58:48
您用[STAThread]属性标记了其中一个方法吗?
发布于 2010-09-24 13:24:24
我建议不要使用多个WaitHandle实例等待完成。使用CountdownEvent类代替。它带来了更优雅和更可伸缩的代码。此外,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");
} 发布于 2010-09-24 05:52:10
你试过为线程设置公寓状态吗?
thread.SetApartmentState (System.Threading.Apartmentstate.MTA );https://stackoverflow.com/questions/3784510
复制相似问题