什么是Task.Start /等待和异步/等待之间的区别? [英] What's the difference between Task.Start/Wait and Async/Await?

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

问题描述

我可能失去了一些东西,但做什么的区别是:

 公共无效的MyMethod()
{
  任务T = Task.Factory.StartNew(DoSomethingThatTakesTime);
  t.Wait();
  UpdateLabelToSayItsComplete();
}公共异步无效的MyMethod()
{
  VAR的结果= Task.Factory.StartNew(DoSomethingThatTakesTime);
  等待结果;
  UpdateLabelToSayItsComplete();
}私人无效DoSomethingThatTakesTime()
{
  Thread.sleep代码(10000);
}


解决方案

  

我可能失去了一些东西。


您的。


  

是做什么的区别 Task.Wait 等待任务


您可以在餐厅服务员订购你的午餐。让您的订单后片刻,一个朋友走在旁边坐下来,你并开始对话。现在你有两个选择。你可以忽略你的朋友,直到任务完成 - 你可以等到你的汤到达并且什么也不做,而你在等待。或者你可以给你的朋友回应,而当你的朋友结束发言时,服务员会为你带来你的汤。

Task.Wait 块,直到任务完成 - 你忽略你的朋友,直到任务完成。 等待处理保持在消息队列中的消息,当任务完成后,排入一个消息,说拿起你等待着之后不放过。你跟你的朋友,当有在汤到达谈话休息。

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

You are.

what is the difference between doing Task.Wait and await 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 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 /等待和异步/等待之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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