Using InvokeRequired when not a Form
I have an event handler, which I want to be handled in the original thread where the object was created, so that it doesn't blo开发者_如何学Cck. With forms, it's easy to use InvokeRequired to force it to the original thread. But how do you do this if your class is not a Form?
Thanks,
PM
This is not going to be easy. First, you will have to create some kind message receiving loop on the thread in question. Then you will need to implement ISynchronizeInvoke
in such a manner that it posts a message containing the delegate to execute into a queue that the target thread can pick up and extract that delegate and execute it. The producer-consumer pattern is often useful for setting this up. The important thing to take away is that you cannot just marshal any delegate onto any thread. The target thread has to be specially designed for this to work. It works in UI threads because Application.Run
gets a message loop going that the Control.Invoke
method uses.
With the Forms/Controls, the invoked delegate gets placed in the UI message pump. Invoking onto the thread that an object was created on would be require some sort of message pump mechanism on that thread.
If it is created on the UI thread, you best bet would be to grab a reference to a UI control and invoke on the UI control. If its a thread created elsewhere, you will have to implement you own mechanism.
Create your background threads with a special name and check Thread.CurrentThread.Name
to see if it is a background or UI.
You can also use Thread.CurrentThread.IsBackground
if you are creating your threads in background so it is false for UI thread.
精彩评论