3 回答

TA貢獻1951條經驗 獲得超3個贊
我可能會遺漏一些東西
你是。
做
Task.Wait
和有await task
什么區別?
你在餐廳的服務員點了午餐。在給出訂單后的一刻,一位朋友走進來,坐在你身邊,開始交談?,F在你有兩個選擇。你可以忽略你的朋友,直到任務完成 - 你可以等到你的湯到來,在你等待的時候什么都不做。或者你可以回復你的朋友,當你的朋友停止說話時,服務員會給你帶來湯。
Task.Wait
阻止任務完成 - 在任務完成之前,您將忽略您的朋友。await
繼續處理消息隊列中的消息,當任務完成時,它會將一條消息列入“在等待之后從中斷處繼續”。你和你的朋友談話,當談話休息時,湯就到了。

TA貢獻1820條經驗 獲得超2個贊
為了演示Eric的答案,這里有一些代碼:
public void ButtonClick(object sender, EventArgs e){ Task t = new Task.Factory.StartNew(DoSomethingThatTakesTime); t.Wait(); //If you press Button2 now you won't see anything in the console //until this task is complete and then the label will be updated! UpdateLabelToSayItsComplete();}public async void ButtonClick(object sender, EventArgs e){ var result = Task.Factory.StartNew(DoSomethingThatTakesTime); await result; //If you press Button2 now you will see stuff in the console and //when the long method returns it will update the label! UpdateLabelToSayItsComplete();}public void Button_2_Click(object sender, EventArgs e){ Console.WriteLine("Button 2 Clicked");}private void DoSomethingThatTakesTime(){ Thread.Sleep(10000);}

TA貢獻1852條經驗 獲得超1個贊
這個例子非常清楚地展示了這種差異 使用async / await,調用線程不會阻塞并繼續執行。
static void Main(string[] args)
{
WriteOutput("Program Begin");
// DoAsTask();
DoAsAsync();
WriteOutput("Program End");
Console.ReadLine();
}
static void DoAsTask()
{
WriteOutput("1 - Starting");
var t = Task.Factory.StartNew<int>(DoSomethingThatTakesTime);
WriteOutput("2 - Task started");
t.Wait();
WriteOutput("3 - Task completed with result: " + t.Result);
}
static async Task DoAsAsync()
{
WriteOutput("1 - Starting");
var t = Task.Factory.StartNew<int>(DoSomethingThatTakesTime);
WriteOutput("2 - Task started");
var result = await t;
WriteOutput("3 - Task completed with result: " + result);
}
static int DoSomethingThatTakesTime()
{
WriteOutput("A - Started something");
Thread.Sleep(1000);
WriteOutput("B - Completed something");
return 123;
}
static void WriteOutput(string message)
{
Console.WriteLine("[{0}] {1}", Thread.CurrentThread.ManagedThreadId, message);
}
DoAsTask輸出:
[1]計劃開始
[1] 1 - 開始
[1] 2 - 任務開始
[3] A - 開始了一些事情
[3] B - 完成了一些事情
[1] 3 - 任務完成,結果:123
[1]程序結束
DoAsAsync輸出:
[1]計劃開始
[1] 1 - 開始
[1] 2 - 任務開始
[3] A - 開始了一些事情
[1]程序結束
[3] B - 完成了一些事情
[3] 3 - 完成任務結果:123
更新:通過在輸出中顯示線程ID來改進示例。
- 3 回答
- 0 關注
- 1652 瀏覽
添加回答
舉報