Task.Start/Wait 和 Async/Await 有什么区别? [英] What's the difference between Task.Start/Wait and Async/Await?

查看:34
本文介绍了Task.Start/Wait 和 Async/Await 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能遗漏了一些东西,但这样做有什么区别:

I may be missing something but what is the difference between doing:

public void MyMethod()
{
  Task t = Task.Factory.StartNew(DoSomethingThatTakesTime);
  t.Wait();
  UpdateLabelToSayItsComplete();
}

public async void MyMethod()
{
  var result = Task.Factory.StartNew(DoSomethingThatTakesTime);
  await result;
  UpdateLabelToSayItsComplete();
}

private void DoSomethingThatTakesTime()
{
  Thread.Sleep(10000);
}

推荐答案

我可能遗漏了一些东西

I may be missing something

你是.

Task.Waitawait task有什么区别?

您从餐厅的服务员那里订购午餐.在您下订单后不久,一位朋友走进来并在您旁边坐下并开始对话.现在你有两个选择.你可以忽略你的朋友,直到任务完成——你可以等到汤上来,在等待的时候什么都不做.或者你可以回复你的朋友,当你的朋友不再说话时,服务员会给你送汤.

You order your lunch from the waiter at the restaurant. A moment after giving your order, a friend walks in and sits down next to you and starts a conversation. Now you have two choices. You can ignore your friend until the task is complete -- you can wait until your soup arrives and do nothing else while you are waiting. Or you can respond to your friend, and when your friend stops talking, the waiter will bring you your soup.

Task.Wait 阻塞直到任务完成——你忽略你的朋友直到任务完成.await 继续处理消息队列中的消息,当任务完成时,它会将一条消息排入队列,该消息表示从等待后停止的地方继续".你和你的朋友交谈,当谈话中断时,汤就来了.

Task.Wait blocks until the task is complete -- you ignore your friend until the task is complete. await keeps processing messages in the message queue, and when the task is complete, it enqueues a message that says "pick up where you left off after that await". You talk to your friend, and when there is a break in the conversation the soup arrives.

这篇关于Task.Start/Wait 和 Async/Await 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆