1

From my understanding, the form and all of its graphical controls run on the main thread. The form is displayed by the main thread and the inputs from the keyboard and mouse are received via the message pump and are executed on that same main thread. I also believe that the code you write also runs on that same thread, unless you create other threads for it to run on. For example, the code you write in the Form1() constructor will run on that same thread. If you make a never ending loop on that thread then the GUI will never display.

How does the code you write for that thread plus the input events received from the message pump all run in the same thread? Also, when you use Invoke on a delegate for it to run on the main thread, how does it get run on the main thread when the main thread already has a list of instructions that it is running. I don't understand how a thread can have a list of instructions that it is executing and then receive some instructions from somewhere else to run also. Does it have code to go periodically check (between running other instructions) some queue? I can understand if 2 execution paths ran on different threads, but don't understand it being on the same thread.

  • "Does it have .. some queue?" Yes. – Euphoric Aug 19 '17 at 3:31
1

The only way you can write code for the message pump thread, commonly called the User Interface (UI) thread, is to put your code into event driven callbacks. These are events in C# terminology. Some events besides mouse, keyboard, etc include the idle event (Application.Idle), which is called when there is no other input to be dispatched.

The delegate to be dispatched on the UI thread will be executed in a similar manner to an Application.Idle handler, or by blocking until the delegate completes. There is only one stack for the UI thread, so it can only execute one call stack at a time. The thread can be pre-empted for other threads to run, but this will not execute additional code for the UI thread.

That said, sometimes you will find reentrant code on windows forms applications. There are certain calls you can make that can cause this situation. Application.DoEvents() can cause event dispatching within the call stack of an event handler. This just deepens the stack; it does not involve any other threads.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.