Baruch
Baruch

Reputation: 21548

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??

Upvotes: 3

Views: 8677

Answers (4)

Moha Dehghan
Moha Dehghan

Reputation: 18472

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.

Upvotes: 4

igrimpe
igrimpe

Reputation: 1785

tutorials or SO answers a recommendation to run the UI on a separate thread ... I doubt that. The UI runs on its own thread anyway. Sometimes it's called the "main" thread of the application. To avoid freezing your app, you do CPU intensive work in other threads. The ways to do this are numerous. Check out Thread, Task, Async, and and and. If you use Framework 4.5 you might use the await SomeTask feature, whenever it is POSSIBLE that the tasks needs more than 20-50 ms to complete - at least this is the recommandation from the MS guys (afaik)

Upvotes: 0

Blorgbeard
Blorgbeard

Reputation: 103585

The UI runs on the main thread. The idea is to run lengthy operations in new threads. Don't do every non-trivial operation in its own thread, but anything that causes the form to go "not responding" is a good candidate for a thread.

In C# it's probably easiest to use a BackgroundWorker instead of rolling your own threads.

Upvotes: 1

Alan
Alan

Reputation: 7951

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.

Upvotes: 2

Related Questions