首页 > 解决方案 > 如果有一些前台线程在控制台上打印一些东西,在主线程完成他的工作后控制台窗口会关闭吗?

问题描述

如果有一些前台线程在控制台上打印一些东西,在主线程完成他的工作后控制台窗口会关闭吗?那么基本上在其他线程中打印的文本会显示在控制台上吗?

类似于以下代码:

public static void Main(string[] args)
        {
            Console.WriteLine("string");

            var threads = new Thread[5];
            for (int i = 0; i < threads.Length; ++i)
            {
                threads[i] = new Thread(() => Console.WriteLine("smth"));
                threads[i].Start();
            }
        }

标签: c#.netmultithreadingconsole-application

解决方案


根据您运行代码的方式(.NET Framework、.NET Core 或 Mono),您应该调整睡眠时间。

public static void Main(string[] args)
{
    Console.WriteLine("string");

    var threads = new Thread[5];
    for (int i = 0; i < threads.Length; ++i)
    {
        threads[i] = new Thread(() => {
            Thread.Sleep(1000);
            Console.WriteLine("smth");
        }) { IsBackground = true };
        threads[i].Start();
    }
}

推荐阅读