C# Parallel.ForEach与ActiveX
我有一点类似的问题。Foreach: 我有一个抽象类和几个派生类。其中一个调用ActiveX元素(webbrowser)。我想使此对象线程安全,但它无法工作:C# Parallel.ForEach与ActiveX,c#,multithreading,user-interface,activexobject,C#,Multithreading,User Interface,Activexobject,我有一点类似的问题。Foreach: 我有一个抽象类和几个派生类。其中一个调用ActiveX元素(webbrowser)。我想使此对象线程安全,但它无法工作: Parallel.ForEach(stringarray, currentfile => { // When we have something, set the thread to STA // So we can call a WebBrowser if (currentfile.Contains("so
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);
}
}
仅在线程启动之前工作
您不能在已经运行的线程上将MTA更改为STA(对于
CurrentThread
),这显然是正确的。我认为您可能需要做一些事情,启动新线程来完成工作。您可能还必须为每个线程创建单独的web浏览器。对于一个网络浏览器来说,这可能有点麻烦。你可以考虑WebCube或者其他方式来制作Web请求。或者我必须用ActiveX提取零件并自己处理它们吗?