无限循环线程

时间:2020-09-06 14:03:38

标签: c#

我是C#的新手,我知道线程是什么,但是我无法真正解释以下示例。

static void Main()
{
    new Thread(new ThreadStart(test))
    {
        IsBackground = true
    }.Start();
}

static void test()
{
    while (true)
    {
        Console.WriteLine("Threads: ");
    }
}

我的程序没有垃圾邮件。
当我尝试使用

static void Main()
{
    test();
}

static void test()
{
    while (true)
    {
        Console.WriteLine("Threads: ");
    }
}

现在循环永远不会结束,为什么? 当我使用线程循环不是无限的。 对不起,我的英语不好

1 个答案:

答案 0 :(得分:1)

退出主程序时,线程将被杀死。

您可以暂停主程序,例如通过等待控制台输入:

static void Main() {
    new Thread(new ThreadStart(test))
    {
        IsBackground = true
    }.Start();
    Console.Read();
}

或者明确地等待线程:

static void Main() {
    var thread = new Thread(new ThreadStart(test))
    {
        IsBackground = true
    }.Start();
    thread.Join();
}

一个更真实的示例将在线程内使用ManualResetEvent或CancellationToken,因此它知道何时停止而不是无限循环

相关问题