NotSupportedException 在 WaitHandle.WaitAll

我正在尝试执行以下代码。 代码正在尝试并行上传和保存图像。 我发送一个图像列表来下载。 我写了它 C# 3.0 并编制了它 .NET Framework 4 /VS.NET express edition/. 手术 WaitAll 导致

NotSupportedException /WaitAlll 对于流中的几个描述符 STA 不支持/

每次我尝试运行我的程序。 我试着删除
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 &lt; 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"/;
}


你能告诉我,了解问题是什么吗?


</string></string>
已邀请:

诸葛浮云

赞同来自:

我不建议你使用多个副本
WaitHandle

等待完成。 相反,使用该类
http://msdn.microsoft.com/en-u ... .aspx
. 这导致更优雅和可扩展的代码。 此外,该方法
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 &lt; imageList.Count; i++/
{
finished.AddCount//;
PicDownloader p = new PicDownloader/imageList[i]/;
picDownloaders[i] = p;
ThreadPool.QueueUserWorkItem/
/state/ =&gt;
{
try
{
p.DoAction
}
finally
{
finished.Signal//;
}
}/;
}
finished.Signal//;
finished.Wait//;
Console.WriteLine/"All pics downloaded"/;
}


</string></string>

郭文康

赞同来自:

你注意到了一个属性方法
[STAThread]

?

喜特乐

赞同来自:

你有没有试图为溪流设置公寓的状态?


thread.SetApartmentState /System.Threading.Apartmentstate.MTA /;

要回复问题请先登录注册