Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java's invokeLater() equivalent in Windows Forms?

Tags:

.net

winforms

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!

like image 329
Aseem Kishore Avatar asked Dec 08 '22 06:12

Aseem Kishore


2 Answers

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.

like image 161
Jon Skeet Avatar answered Dec 09 '22 19:12

Jon Skeet


Have you looked into the BackgroundWorker?

like image 45
Erik Avatar answered Dec 09 '22 20:12

Erik