在多線程程序中使用Console.ReadKey()
時出現奇怪的問題。具有多線程的Console.ReadKey()的奇怪行爲
我的問題是:爲什麼會發生這種情況?這是一個錯誤,還是因爲我在濫用Console
? (請注意,控制檯是應該是線程安全的,according to the documentation)
這是最簡單的代碼來解釋這一點:
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.");
}
}
}
你覺得這會打印出來,如果你運行它,並唐't按下一個鍵?
答案就是你所期望:
X
Entering the test() function.
Exiting the test() function.
現在註釋掉Console.WriteLine("X")
並重新運行(不按任何鍵)。 我期望看到此輸出:
Entering the test() function.
Exiting the test() function.
相反,我看到什麼。然後當我按下一個鍵,它說:
Entering the test() function.
......就是這樣。該程序退出(當然),它沒有時間去下一個WriteLine()
。
我覺得這種行爲很神祕。這很容易解決,但我對它爲什麼會發生感興趣。
[編輯]
如果我添加它的工作一個Thread.Sleep(1)
立即Console.ReadKey()
之前預期。當然,這不應該是必要的,因爲無論如何,Console.ReadKey()
應該永遠等待。
所以看起來它可能是某種競爭條件?
更多信息:Servy發現(並且我重複了)Console.WriteLine("Entering the test() function.")
行被阻塞,直到按下任何鍵。
構建配置
的Visual Studio 2012,Windows 7的64位,四核,英語(英國)。
我已經嘗試過.Net4,.Net4.5,x86,AnyCPU以及調試和發佈的所有組合,並且它們都不能在我的PC上運行。但發生了一件非常奇怪的事情。它在我第一次嘗試使用.Net4的AnyCPU版本時開始工作,但之後它再次停止工作。看起來非常像隻影響某些系統的競爭條件。
根據我的實驗有一些初始化,發生第一次控制檯將被寫入建立了框架,併發讀取和寫入。如果在你第一次調用'ReadKey'之前控制檯已經寫好了,你會沒事的,但是從未寫過這個特定的行爲。正如你所說,易於解決,但很好奇。 – Servy 2013-02-28 19:36:21
當您明確強制Console.Out刷新時會發生什麼? – Krypes 2013-02-28 19:36:26
@Krypes'Console.WriteLine'塊(基於我的實驗),而不是繼續,不做任何事情,所以沒有機會刷新它。 – Servy 2013-02-28 19:37:12