我在使用时遇到一个奇怪的问题Console.ReadKey()
在多线程程序中。
我的问题是:为什么会发生这种情况?这是一个错误,还是因为我滥用了Console
?
(请注意,控制台是supposed为了线程安全,根据文档 http://msdn.microsoft.com/en-us/library/43zwz7ys.aspx.)
用代码来解释这一点是最简单的:
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.");
}
}
}
如果你运行它,你认为会打印出什么don't按一个键?
答案正是你所期望的:
X
Entering the test() function.
Exiting the test() function.
现在注释掉Console.WriteLine("X")
并再次运行它(无需按键)。
我期望看到这个输出:
Entering the test() function.
Exiting the test() function.
相反,我看到nothing。然后当我按下一个键时,它会说:
Entering the test() function.
...就是这样。程序退出(当然)并且没有时间进入下一个WriteLine()
.
我觉得这种行为非常神秘。这很容易解决,但我很好奇为什么会发生这种情况。
[EDIT]
如果我添加一个Thread.Sleep(1)
就在之前Console.ReadKey()
它确实按预期工作。当然,这不应该是必要的,因为Console.ReadKey()
无论如何应该永远等待。
所以看起来这可能是某种竞争条件?
更多信息:Servy 发现(并且我复制了)该行Console.WriteLine("Entering the test() function.")
一直处于阻塞状态,直到按下任意键为止。
构建配置
Visual Studio 2012、Windows 7 x64、四核、英语(英国)。
我已经尝试了.Net4、.Net4.5、x86、AnyCPU 以及调试和发布的所有组合,但它们都无法在我的电脑上工作。但发生了一件非常奇怪的事情。当我第一次尝试 .Net4 的 AnyCPU 版本时它开始工作,但随后又停止工作。看起来很像只影响某些系统的竞争条件。