Why does the main thread's output come first in C#?

前端 未结 7 2189
半阙折子戏
半阙折子戏 2021-02-04 23:41

I wrote this little program:

class Program
{
    static void Main(string[] args)
    {
        Thread t = new Thread(WriteX);
        t.Start();

        for (in         


        
7条回答
  •  说谎
    说谎 (楼主)
    2021-02-04 23:59

    This is probably because Thread.Start first causes the change of state of thread on which it is called and OS schedules it for execution whereas the main thread is already running and does not need these two steps. This is probably the reason that the statement in main thread executes first rather the one in the newly created thread. Keep in mind the sequence of thread execution is not guaranteed.

    Thread.Start Method

    1) Thread.Start Method Causes the operating system to change the state of the current instance to ThreadState.Running.

    2) Once a thread is in the ThreadState.Running state, the operating system can schedule it for execution. The thread begins executing at the first line of the method represented by the ThreadStart

    Edit It seems to me that representing this in graphical form will make this more clear and understandable. I tried to show the sequence of thread execution in diagram below.

    enter image description here

提交回复
热议问题