从后台线程创建Windows窗体

问题描述

| 我正在开发VS Package,但遇到了以下问题: 我有一个Background-Thread,它每隔几秒钟检查一次必须完成的特定更改。这包括更改VS 2010的GUI,由于某种原因,它无需调用即可完美运行。 无论如何,如果我尝试打开一个新窗体,它会打开,但它不会显示任何内容,会导致崩溃,并且不会响应。 我已经尝试过
Application.OpenForms[0].invoke( /* delegate to create the form */)
。 这个工作正常,但我一直都没有开放的表单。 我也曾尝试创建System.Windows.Forms.Timer,但是它并不是从头开始的。 问题:如何获取正确的GUI线程来调用我的表单? 或者更确切地说:如何从后台线程创建新表单?     

解决方法

当主应用程序启动时,将SynchronizationContext.Current实例存储在某个位置。 一旦设置。 您可以尝试在其他任何线程中遵循以下代码。
 GuiContext.Send(_ => {
                        Form2 frm2=new Form2();
                        frm2.ShowDialog();
                       },null);
其中GuiContext是SynContext的存储实例。     ,没有任何全局变量的另一种方法是(对VB.NET很抱歉-在VB.NET中这样做):
 Dim result as Object
 Dim deleg As ThreadStart = Sub() result = DoSomethingHere()
 If Thread.CurrentThread.GetApartmentState <> ApartmentState.STA Then
 Dim t As New Thread(deleg)
     t.SetApartmentState(ApartmentState.STA) \'Set the thread to STA
     t.Start()
     t.Join() \'Wait for the thread to end
 Else
     deleg.Invoke()
 End If