Handling Background Events on the Main Thread
I create a backgro开发者_如何学编程und thread to do some work and, at the very end, I call a method ThreadDone(threadWorkResult)
which raises an event. Currently, the event handler runs on the same background thread but I would like it to run on the main UI thread (Forms application). I searched online and found something about using attributes here but would like to know how to do this programatically. Is there any way it can be done outside the body of the handler itself?
I looked into BackgroundWorker but I have to create several threads at once so all of the respective OnWorkerCompleted event handlers become quite messy; more importantly, not all of them require the completed event. Worst case scenario I will use several BackgroundWorkers but is it possible for me to simply call a method (void aMethod()
) from a background thread and force it to run on the primary UI thread?
There is a method called BeginInvoke
on Windows Form controls which will execute code in the GUI thread.
I would recommend you to use BackgroundWorker thread for the background work and you can then easily handle the UI in the OnWorkerCompleted event.
Look at my answer here for more information.
Edit
You can use a delegate to hand over some tasks to MainUI thread.
public delegate void MyDelegate(object paramObject);
In the background thread call it as below.
private void aMethod(object myParam)
{
if (InvokeRequired)
{
// We're not in the UI thread, so we need to call BeginInvoke
BeginInvoke(new MyDelegate(aMethod), new object());
return;
}
// Must be on the UI thread if we've got this far.
// Do UI updates here.
}
See here and here for references.
精彩评论