Search code examples
c#winformsthread-safetyui-threadshowdialog

Do all the WinForms application windows share the same thread?


A WinForms app of mine does NOT execute Application.Run(Form) immediately on starting.

It initialises some variables first, accessing the command line parameters, the application configuration API, other external stuff and, in particular, forms (e.g. a sign-in form) instantiated (and configured by passing some of the values set previously) with using and displayed with ShowDialog.

Then it executes Application.Run(Form) to display the main form but the main form can display other forms (mostly with ShowDialog) too in its turn. All the forms are defined in a separate class library. Many of them (the windows) need to access objects instantiated in the Program.Main(string[] args) (yes, I have added the string[] args part although WinForms apps created with Visual Studio don't have it by default) and pass objects to each-other;

This makes me worry about thread-safety but the basic idea I have about the "UI thread" concept suggests my worries might be false.

So, do all the windows (Form instances) instantiated and shown by the same WinForms application process share the same UI thread (unless I put the code instantiating/showing them in an asynchronously ran Task or something like that explicitly of course)? Or should I actually use some special techniques (specific suggestions are appreciated) to pass data between them safely?


Solution

  • It's a bit hard to answer your question because there could always be "... but I'm creating some threads here and there ..." lurking that you're not telling us.

    However, barring that, then yes. A Winforms application will use 1 thread for its user interface and all surrounding code.

    Be aware that if you start mucking about with the following:

    • Task.Run
    • Thread class
    • BackgroundWorker

    then my answer goes out the window.