Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In WinForms, Is More than One Thread Possible in the UI?

I think the answer is no. I checked similar questions on stackoverflow, but they seem to go different directions based on what was needed for the specific solutions (but may have missed something).

Is it ever possible to have more than a single UI thread in a WinForms application? I am refactoring and wondering if I should use ConcurrentDictionary or Dictionary that would be accessed from those thread(s) accessing forms. This is for a larger body of code with multiple developers/designs and I want to make the choice as solid as possible (but not over engineer it). Since I am looking for a general answer, specifics are not in this question although they usually are. Thanks for looking and any help - much appreciated.

like image 325
Buck Avatar asked Dec 09 '25 22:12

Buck


1 Answers

Yes it can be done, but it's usually wrong to do so. Multiple UI Threads - Winforms

Every sensible GUI design I've ever encountered always uses a single UI thread, even if the framework allows for more than that. The single exception I can see are independent windows living in their own threads and accessing shared data from a Model that lives in a different thread, but the benefits from such a design are limited. (Edit: In some cases a better alternative to using multiple UI threads is to use different processes for different windows - like tabs in browsers - as this allows the main application to recover e.g. if a window corrupts the heap.)

However, for any reasonably advanced application there will be multiple non-UI background threads.

Because you are asking in the context of thread-safety, I'd suggest keeping the MVVM and MVP patterns in mind. If your structure lives in View, Presenter, or ViewModel, it doesn't need thread safety. The Model often lives in, or talks with, a different thread - e.g. if it's a database or a wrapper over a database. So threadsafety is usually part of the design of the Model, or part of the communication of the Model with the ViewModel/Presenter.

See MVVM: Tutorial from start to finish?, What are MVP and MVC and what is the difference?

like image 74
Peter Avatar answered Dec 11 '25 12:12

Peter