2017-08-12 17 views
0

我想要在需要提醒時打開在線程(非主線程)中具有webBrowser控件的小型彈出窗體。c#在線程中創建具有webBrowser的表格

只要運行在線程中彈出的形式,得到了錯誤

ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be 
instantiated 
because the current thread is not in a single-threaded apartment. 

所以,我設置與STA模式的線,不會發生錯誤。但是,當需要運行多個彈出窗口時,它們會逐個顯示出來。第二個彈出窗口不會出現,直到我關閉第一個彈出窗口依此類推。 我想在線程中同時顯示每個彈出窗口。

private void timer1_Tick(object sender, EventArgs e) 
{ 
    Thread th = new Thread(() => 
    { 
     var arts = _Moniter.Mon(); 
     if (arts.Count < 1) return; 

     foreach (var art in arts) 
     { 
      var f = new FormPopup(art, FormPopup.POPUP_MODE.NORMAL, Color.Yellow, 30000); 
      Application.Run(f); 
     } 
    }); 
    th.SetApartmentState(ApartmentState.STA); // 
    th.IsBackground = true; // 
    th.Start(); 
} 

有沒有什麼方法可以顯示在沒有STA線程中有webBrowser的窗體? 或者我怎樣才能與STA線程同時運行多個窗體?

+0

爲什麼你想要在一個單獨的線程中運行它?爲什麼不在'f.Show();'中替換'Applicatio.Run(f);'來顯示多個表單併發? –

+0

@PeterBons當我使用「f.Show();」運行時,所有彈出窗體在顯示後立即關閉。所以,我使用了Application.Run()。監視器工作時,我只想UI不會卡住。因爲這個工作包含網絡解析的東西。 – amplet7

回答

0

我自己解決了問題。只需在「主窗體」的Invoke()中創建並調用彈出窗體即可。也不需要使用STA線程。這樣做可能會產生其他副作用。但是,它看起來工作正常。

private void timer1_Tick(object sender, EventArgs e) 
{ 
    Thread th = new Thread(() => 
    { 
     foreach (var art in arts) 
     { 
      this.Invoke((MethodInvoker)(() => // It works! 
      { 
       var f = new FormPopup(art, FormPopup.POPUP_MODE.NORMAL, Color.Yellow, 30000); 
       f.Show(); 
      })); 
     } 
    }); 
    th.IsBackground = true; // 
    th.Start(); 
}