3 回答
TA贡献1951条经验 获得超3个赞
我可能会遗漏一些东西
你是。
做
Task.Wait
和有await task
什么区别?
你在餐厅的服务员点了午餐。在给出订单后的一刻,一位朋友走进来,坐在你身边,开始交谈。现在你有两个选择。你可以忽略你的朋友,直到任务完成 - 你可以等到你的汤到来,在你等待的时候什么都不做。或者你可以回复你的朋友,当你的朋友停止说话时,服务员会给你带来汤。
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 关注
- 1627 浏览
添加回答
举报