简体   繁体   中英

How to create multiple threaded Forms as MDIChild

Is it possible to have multiple threaded forms as MDIChild? I have an ActiveX control in MdiChild form that can take a lot of processing CPU, and would like to make that one control will not influence another control by using sample code below. But line frmDoc.MdiParent = Me throws cross threading exception.

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()

Throws System.InvalidOperationException was unhandled:

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

GUI elements must be initialized and accessed in the main event loop only. You can process heavy calculations asynchronously or in background threads.

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

Perform all the heavy opration in DoWork event and use the ProgressChanged/RunWorkerCompleted event to update the UI elements.

Available options on how to implement this

Just found a good msdn support article How To Create Windows in a Multithreaded Application

Creating a window can force an implicit AttachThreadInput (), when a parent window is created in one thread and the child window is being created in another thread. When windows are created (or set) in separate threads with a parent-child relationship, the input queues are attached.

More information can be found on Walkthrough: Supporting COM Interop by Displaying Each Windows Form on Its Own Thread

Similar question was asked Spawn a new thread to open a new window and close it from a different thread

But, anfortunatelly non of those have anything about child forms.

Update: Just have found bugs in Walkthrough code; but overall this sample has some good ideas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM