我对 Parallel.Foreach 有一点问题:我有一个抽象类和一些派生类。其中之一称为 ActiveX 元素(网络浏览器)。我想让这个对象线程安全,但它不起作用:
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);
}
}