1

I create a background 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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
john
  • 4,043
  • 7
  • 27
  • 39

2 Answers2

2

There is a method called BeginInvoke on Windows Form controls which will execute code in the GUI thread.

Andy Kershaw
  • 191
  • 7
0

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.

Community
  • 1
  • 1
CharithJ
  • 46,289
  • 20
  • 116
  • 131
  • Thanks for the reply! I may be missing something but doesn't `InvokeRequired` (and `BeginInvoke` for that matter) require a control to be called (i.e. `aControl.InvokeRequired`)? Also, the `MyDelegate` you call out has a signature of void (void) but is being passed `object value` as parameter. Is this possible? And, did you mean to write `UpdateMyUI` instead of `UpdateStatus` in `BeginInvoke`? Like I mentioned previously, I am quite new to C# so I apologize if I just asked a (or several) stupid questions. :) – john Aug 04 '11 at 14:19
  • @ Jon : Thank you for pointing my errors. I had posted untested code. aControl.InvokeRequired is possible. – CharithJ Aug 04 '11 at 22:42