tags:

views:

467

answers:

2

I'm new to Windows Forms from the Java Swing world. Is there any equivalent for Java's SwingUtilities.invokeLater()? Or, how can I dispatch a task to be run on the main Windows Forms event thread?

I'm performing a background task using a synchronous API on a separate thread. At the end of the task, I want to re-enable some disabled buttons. But when I attempt to do so, I get an exception (rightly so) because I'm modifying the UI on a non-UI thread.

How can I enqueue that action to run on the main event thread? I haven't found the answer searching both the web and SO, I'm guessing because I'm not asking the question the right way. Any help is appreciated -- thanks!

+1  A: 

Have you looked into the BackgroundWorker?

Erik
Thanks Erik. I was aware of BackgroundWorker, and I'll be wrapping my currently synchronous API in that eventually. For now, I just wanted to wrap a UI around a command-line tool, so just needed a quick and easy way of executing it on a separate thread.
Aseem Kishore
+8  A: 

You can execute a delegate on the UI thread using Control.Invoke or Control.BeginInvoke. An alternative is to use BackgroundWorker, which wraps all this up nicely - it's handy if you only ever want to do one thing during the processing and one thing on completion, but if you want to perform arbitrary operations on the UI, using Invoke/BeginInvoke is more flexible.

I have a page on using Invoke/BeginInvoke in my threading tutorial. (It doesn't cover BackgroundWorker, I'm afraid.)

You might also want to look at Joe Albahari's threading tutorial.

Jon Skeet
Thanks Jon! That tutorial seems very useful.
Aseem Kishore