Console.ReadKey()在多线程程序中使用时,我遇到了一个奇怪的问题.
我的问题是:为什么会这样?这是一个错误,还是因为我在滥用Console?(请注意,根据文档,控制台应该是线程安全的.)
用代码解释这个是最容易的:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("X"); // Also try with this line commented out.
Task.Factory.StartNew(test);
Console.ReadKey();
}
private static void test()
{
Console.WriteLine("Entering the test() function.");
Thread.Sleep(1000);
Console.WriteLine("Exiting the test() function.");
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你运行它并且没有按键,你认为会打印出什么?
答案正是您所期望的:
X
Entering the test() function.
Exiting the test() function.
Run Code Online (Sandbox Code Playgroud)
现在注释掉Console.WriteLine("X")并再次运行它(不按键).我希望看到这个输出:
Entering the test() function. …Run Code Online (Sandbox Code Playgroud)