使用Async做同样事情的多种方法? [英] Multiple ways to do the same thing using Async ?

查看:100
本文介绍了使用Async做同样事情的多种方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


在我看来,至少有三种不同的方式来编写系数


1)定义一个任务并传递一个lambda表达式,其中包含我需要执行的代码,然后使用Task.Wait等待结果


示例:


任务= t = Task.Factory.StartNew(在此处传递代码);


t.Wait()


/ /在此处继续您的代码



2)定义任务< T>并传递一个函数,该函数返回一个T,然后可以通过任务上的.Result方法使用。


示例:


任务< T> ; T&NBSP; = Task.Factory.StartNew(此处传递代码返回T>


int result = t.Result; //隐式调用.Wait



3)编写一个返回Task< T>的方法。并使用await关键字





< span style ="color:#2b91af; font-size:small"> 公共任务 < T>加载 东西 Async()





{.. do work ..}





var结果=等待LoadSomethingAsync


我对此感到困惑:


1)我不确定这些是否与使用TPL


2)是否存在首选项?





解决方案

选项#1和#2之间的唯一区别是显而易见的:#2返回一个值。


但使用Wait()与使用await相同(如果是的话,就没有必要等待了。)


你可能想看一下async-await的一些介绍,比如
MSDN上的那个
,它解释了等待实际做的事情。另外,Stack Overflow上有一个问题可以回答这个问题:
Task.Start / Wait和Async /之间有什么区别?等待?


There appears to me that there are at least three different ways to write coee

1) define a task and pass it a lambda expression with the code I need to execute adn then use Task.Wait to wait for result

Example:

Task = t = Task.Factory.StartNew (pass code here);

t.Wait()

// continue your code here

 

2) Define a task <T> and pass it a function that returns a T which can then be used via the .Result method on the task.

Example:

Task<T> t  = Task.Factory.StartNew (pass code here that returns T>

int result = t.Result; // has implicit call to .Wait

 

3) write a method that returns a Task<T> and use the await keyword


public Task<T> LoadSomethingAsync()


{.. do work..}


var result = await LoadSomethingAsync

What I am confused about:

1) I am not sure if these are all the similar ways to doing something using the TPL

2) Is there preference one over the other ?



解决方案

The only difference between options #1 and #2 is the obvious one: #2 returns a value.

But using Wait() is not the same as using await (if it was, there would be no need for await).

You might want to have a look at some introduction of async-await, like the one on MSDN, which explains what await actually does. Also, there is question on Stack Overflow that answers exactly this question: What's the difference between Task.Start/Wait and Async/Await?


这篇关于使用Async做同样事情的多种方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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