Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# UI on separate thread

I keep seeing on various forums, tutorials or SO answers a recommendation to run the UI on a separate thread then the rest of the program to keep it responsive.
How is this done in practice? Does it mean editing program.cs to start a thread before loading the form? Or does it mean that any non-trivial operation activated from within the form fork a thread and use that? Or is it some setting? How do you work with it??

like image 919
Baruch Avatar asked Aug 25 '26 08:08

Baruch


2 Answers

To keep UI responsive you should run other time consuming operations in a separate thread. Usually user interface operations should be done in .NET's main (UI) thread.

There are several ways to use a separate (background) thread for your operations. For Windows Forms applications, simplest option is BackgroundWorker component.

You can also create a Thread object yourself. But you should be careful about calling UI methods or changing UI controls properties in created thread. As I said, all the user interface operations (showing forms, changing controls texts or locations and so on) should be done in UI thread. Otherwise you get an exception. To do that, you can use Control.Invoke method.

like image 99
Mohammad Dehghan Avatar answered Aug 27 '26 21:08

Mohammad Dehghan


Typically in a C# WinForms application the Program.cs launches your main form like so.

Application.Run(new MyMainForm());

This creates your main dispatcher (GUI) thread where all of your events are fired on, (button click, form load etc) In practice, if you need to execute a long computation, you would create a new background worker thread and use that and the Invoke back to the event dispatcher when you were finished to update the UI.

If you execute a long process on the UI thread it will lock the UI and it will become unresponsive.

like image 29
Alan Avatar answered Aug 27 '26 21:08

Alan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!