如何创建多个线程窗体作为MDI子

时间:2012-09-20 04:04:05

标签: .net vb.net

是否可以将多个线程表单作为MDIChild?我有一个MdiChild形式的ActiveX控件,它可以占用大量的处理CPU,并希望通过使用下面的示例代码使一个控件不会影响另一个控件。但是行frmDoc.MdiParent = Me抛出了交叉线程异常。

Dim frmDoc As MDIChild
Dim newThread As New Thread(
    Sub()
        frmDoc = New MDIChild
        frmDoc.MdiParent = Me '<- this line throws cross threading exception.
        Application.Run(frmDoc)
    End Sub
)
newThread.IsBackground = True
newThread.SetApartmentState(ApartmentState.STA)
newThread.Start()

抛出System.InvalidOperationException未处理:

Message=Cross-thread operation not valid: 
  Control 'FormMdiApp' accessed from a thread other than the thread it was created on.
Source=System.Windows.Forms

3 个答案:

答案 0 :(得分:3)

必须仅在主事件循环中初始化和访问GUI元素。您可以异步或后台线程处理繁重的计算。

答案 1 :(得分:1)

尝试BackgroundWorker http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=vs.95).aspx

在DoWork事件中执行所有繁重操作,并使用ProgressChanged / RunWorkerCompleted事件更新UI元素。

答案 2 :(得分:0)

有关如何实施此

的可用选项

刚刚找到了一篇很好的msdn支持文章How To Create Windows in a Multithreaded Application

  

当a时,创建窗口会强制隐式AttachThreadInput()   父窗口在一个线程中创建,子窗口正在生成   在另一个线程中创建。当窗口被创建(或设置)时   具有父子关系的单独线程,输入队列   附上。

可以找到更多信息 Walkthrough: Supporting COM Interop by Displaying Each Windows Form on Its Own Thread

类似问题被问到Spawn a new thread to open a new window and close it from a different thread

但是,很幸运的是,没有任何关于儿童形式的东西。

更新:刚刚在Walkthrough代码中发现了错误;但总的来说这个样本有一些好主意。