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!
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.
Have you looked into the BackgroundWorker?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With