2017-08-12 19 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(); 
}