为什么主线程的输出来首次在C#中? [英] Why does the main thread's output come first in C#?

查看:138
本文介绍了为什么主线程的输出来首次在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个小程序:

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

        for (int i = 0; i < 1000; i++)
        {
            Console.Write("O");
        }
    }

    private static void WriteX()
    {
        for (int i = 0; i < 1000; i++)
        {
            Console.Write(".");
        }
    }
}



我跑了大约五十次,并在控制台上的第一个字符总是O。这是奇怪的我,因为 T 线程开始首先然后在主仍在继续。

I ran it about fifty times, and the first character on the console was always "O". It is weird for me, because the t thread starts first then the main continues.

有没有任何解释此?

推荐答案

这可能是因为Thread.Start首先使上调用它和操作系统调度线程的状态变化它执行的,而的在主线程已经运行,不需要这两个步骤即可。这可能是在主线程执行语句,而第一个在新创建的线程的原因。记住线程执行的顺序不能保证。

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.

主题。起动方法

1)Thread.Start方法导致操作系统来改变$ b $的状态b当前实例到ThreadState.Running。

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

2)一旦一个线程处于ThreadState.Running状态下,操作
系统可以安排用于执行。线程开始在$ B $执行甲乙经的ThreadStart

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.

这篇关于为什么主线程的输出来首次在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆