我有一個控制檯應用程序,它從Console.OpenStandardInput()讀取消息; 我正在做這個任務。但它似乎不起作用。Task.Factory.StartNew無法在控制檯c#應用程序中工作
static void Main(string[] args)
{
wtoken = new CancellationTokenSource();
readInputStream = Task.Factory.StartNew(() =>
{
wtoken.Token.ThrowIfCancellationRequested();
while (true)
{
if (wtoken.Token.IsCancellationRequested)
{
wtoken.Token.ThrowIfCancellationRequested();
}
else
{
OpenStandardStreamIn();
}
}
}, wtoken.Token
);
Console.ReadLine();
}
這裏是我的OpenStandardStreamIn功能
public static void OpenStandardStreamIn()
{
Stream stdin = Console.OpenStandardInput();
int length = 0;
byte[] bytes = new byte[4];
stdin.Read(bytes, 0, 4);
length = System.BitConverter.ToInt32(bytes, 0);
string input = "";
for (int i = 0; i < length; i++)
{
input += (char)stdin.ReadByte();
}
Console.Write(input);
}
任何幫助嗎?爲什麼它不能連續循環工作
「不工作」是什麼意思?究竟會發生什麼? – galenus 2014-11-04 06:37:10
你在說什麼循環?如果這是你想要做的,你還沒有開始任何循環的新任務。你還沒有等待在ReadLine之前完成的Task。 – bit 2014-11-04 06:38:44
@galenus:它只是在編譯時經歷一次,然後開始等待Console.ReadLine()的輸入。當我添加輸入它正在完成和dubugging停止 – 2014-11-04 06:40:26