2012-12-11 49 views
0

我有一個Parallel.Foreach小問題: 我有一個抽象類和一些派生類。其中一個叫ActiveX元素(網頁瀏覽器)。我想使這個對象線程安全的,但它不會工作: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); 
    } 
} 

回答

1

SetApartmentState線程啓動僅以前一樣工作。

在已經運行的線程上,您不能將MTA更改爲STA(這對於CurrentThread顯然是正確的)。

+1

那麼是否有機會處理這種情況? 或者我必須用ActiveX提取零件並自行處理它們? – Link

0

我想你可能不得不做一些事情,你啓動新線程來完成這項工作。您可能還必須爲每個線程創建單獨的Web瀏覽器。這可能只是一個網頁瀏覽器有點毛。您可以考慮使用WebClient或其他方式來發出Web請求。