我对 Parallel.Foreach 有一点问题:我有一个抽象类和一些派生类。其中一个调用ActiveX元素(Web浏览器)。我想使这个对象线程安全,但它不起作用:
Parallel.ForEach(stringarray, currentfile =>
{
// When we have something, set the thread to STA
// So we can call a WebBrowser
if (currentfile.Contains("something"))
Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
// Here is the part where the WebBrowser is called
// But it fails and the debugger says that
// Thread.CurrentThread.ApartmentState is MTA, but the condition above
// is true
obj track = IService.Create(currentfile);
if (track != null)
{
lock(my_list)
my_list.Add(track);
}
}
SetApartmentState 仅在线程启动之前工作。
您不能在已经运行的线程上将 MTA 更改为 STA(对于CurrentThread
来说显然是正确的)。
我认为您可能必须做一些事情来启动新线程来完成工作。 您可能还必须为每个线程创建单独的 Web 浏览器。 对于网络浏览器来说,这可能会变得有点毛茸茸的。 您可以考虑使用WebClient或其他方式来发出Web请求。