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.InvokeorControl.BeginInvoke. An alternative is to useBackgroundWorker, 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, usingInvoke/BeginInvokeis more flexible.I have a page on using
Invoke/BeginInvokein my threading tutorial. (It doesn’t coverBackgroundWorker, I’m afraid.)You might also want to look at Joe Albahari’s threading tutorial.