I've written a class which does some long running background processing and
returns multiple results via events. The class has an Execute() method which
creates a thread and runs an internal method _execute() on it.
When events fire they are running on the worker thread. To use this class
from a form with event handlers that manipulate the UI, you have to write
this
public void MyForm_DocumentReady(object Sender, DocumentReadyEventArgs e) {
if (InvokeRequired)
Invoke(new DocumentReadyDelegate(MyForm_DocumentReady), new object[]
{Sender, e);
else {
//do stuff on UI thread
}
}
But I can't expect people to know they have to do that!
Invoke() searches for the root windowed parent of the control on which it is
invoked, and marshals to that thread. If I made the class a derivative of
Control I could do the marshalling internally using Invoke. But this class
won't necessarily be a parented control.
Getting a reference to the thread that calls Execute() is easy. You just
take snaffle a reference to the current thread when entering the Execute()
method. Can anyone tell me how to say, "run this method on that thread"
without using Invoke?