100分求“不支持一个 STA 线程上针对多个句柄的 WaitAll。”的解决方案
下面是一个多线程下载文件的c/s程序,代码在进行多线程下载的过程中在运行到WaitHandle.WaitAll(events);这句时出现了这个错误:
“不支持一个 STA 线程上针对多个句柄的 WaitAll。”
代码如下:
//多线程备份文件
public bool mutiThreadUploadFile(string fileName)
{
FileInfo fi = new FileInfo(fileName);
if (fi.Exists)
{
button5.Enabled = false;//Avoid upload twice
//初始信号
ManualResetEvent[] events = new ManualResetEvent[5];
//分块——分成5块下载
int nTotalBytes = (int)(fi.Length / 5);
for (int i = 0; i < 5; i++)
{
events[i] = new ManualResetEvent(false);
FileThread thdSub = new FileThread(
i * nTotalBytes,
(fi.Length - i * nTotalBytes) > nTotalBytes ? nTotalBytes : (int)(fi.Length - i * nTotalBytes),
fi.FullName);
ThreadPool.QueueUserWorkItem(new WaitCallback(thdSub.UploadFile), events[i]);
}
//等待进程结束
WaitHandle.WaitAll(events);//错误指向了这句(“不支持一个 STA 线程上针对多个句柄的 WaitAll。”
)
//重置 button 状态
button5.Enabled = true;
return true;
}
else
return false;
}
请高手指教!该如何解决呢?
[解决办法]
把开始的那个[STA]改下
好像是[MTA]?? 不记得了........搜下多线程
[解决办法]
对 改成[MTAThread]
[解决办法]
楼上的没有用,
[MTAThread] COM 线程模型只适用于使用 COM interop 的应用程序。如果将此属性应用到不使用 COM interop 的应用程序,将没有任何效果。
另外楼主不要把bs和cs程序运行模式混淆。