Bulk multithreaded message without a second form

I have a C # application that uses a COM component. This COM component requires a message pump (Application.Run ()) to process it. This means that it is stuck on the main thread. But I recently discovered that you can run another Application.Run in another thread that gets its own ApplicationContext.

Therefore, I want to place the COM component in my own thread inside its own Application.Run (), but I cannot figure out how to start working on a new thread without creating a user interface form.

WindowsFormsSynchronizationContext I need to contact a thread that is not created before Application.Run (). But as soon as Application.Run () is called, I cannot figure out how to get to the SynchronizationContext. If I could just pick up one event in this thread, I could use this to load it all (create a COM object, etc.), but it seems that nowhere needs to be hooked on a new event loop without a form.

I tried all kinds of confusing things, such as setting a message filter (no messages appeared in the new thread), copying the execution context to another thread and trying to extract the SynchronizationContext from it (it refuses to copy the ExecutionContext of the already running thread), retrieving Thread.CurrentContext before starting Application .Run (), and then calling DoCallbBack () (DoCallback ends in the original thread), etc. Nothing I tried works.

+4
source share
1 answer

Bryce

You might be able to adapt this snippet from Anders Halesberg talking about "The Future of C #". This is a small class that adds a message to the pump so that it can open windows using the REPL loop and they will be attached to them using the message pump.

The code is as follows:

using System.Windows.Forms; using System.Threading; class UserInterfaceThread() { static Form window; public UserInterfaceThread() { var thread = new Thread(() => { window = new Form(); var handle = window.Handle; Application.Run(); }); thread.Start(); } public void Run(Action action) { window.Invoke(action); } } 

The discussion of this code takes place after 1 hour 5 minutes in Anders conversation, if you want to view it.

+6
source

All Articles