简体   繁体   English

为什么使用async并等待Task <>?

[英]Why use async and await with Task<>?

If I have a normal method that I want to make asynchronous: 如果我有一个我想要异步的普通方法:

public int Foo(){}

I would do: 我会做:

public Task<int> FooAsync(){
    return Task.Run(() => Foo());
}

Why would I do: 我为什么这样做:

public async Task<int> FooAsync(){
    return await Task.Run(() => Foo());
}

The way I plan to use this is: 我计划使用它的方式是:

FooAsync().ContinueWith((res) => {});

I want the method to just run without stopping, but I want something like a callback to be fired, hence the ContinueWith . 我希望该方法只是在不停止的情况下运行,但我希望触发类似回调的东西,因此是ContinueWith But with the second version, is there a point to using it? 但是对于第二个版本,有没有必要使用它?

In my understanding, you only need async and await when you write a method which does some async calls inside, but you would like it to look like it doesn't . 根据我的理解,你只需要asyncawait你编写一个在内部执行异步调用的方法,但你希望它看起来不像 In other words you want to write and read code as if it was some normal sequential code, handle exceptions as if it was normal sequential code, return values as if it was normal sequential code and so on. 换句话说,您希望编写和读取代码,就像它是一些正常的顺序代码一样,处理异常就好像它是正常的顺序代码一样,返回值就好像它是正常的顺序代码一样。 Then compiler's responsibility is to rewrite that code with all the necessary callbacks preserving the logic. 然后编译器的责任是用保留逻辑的所有必要的回调重写该代码。

Your method is so simple I don't think it needs that rewriting at all, you can just return the task, but whoever consumes it may want to await for its return value. 你的方法很简单我认为它根本不需要重写,你可以只返回任务,但是消费它的人可能想要await它的返回值。

Why would I do: 我为什么这样做:

  public async Task<int> FooAsync() { return await Task.Run(() => Foo()); } 

You wouldn't. 你不会。 Your previous version returns Task which is already awaitable. 您以前的版本返回已经等待的任务。 This new version doesn't add anything. 这个新版本不会添加任何内容。

The way I plan to use this is: 我计划使用它的方式是:

  FooAsync().ContinueWith((res) => {}); 

I want the method to just run without stopping, but I want something like a callback to be fired, hence the ContinueWith. 我希望该方法只是在不停止的情况下运行,但我希望触发类似回调的东西,因此是ContinueWith。

This is where the difference comes in. Let's flesh out your example a little bit: 这就是差异所在。让我们充实你的榜样:

void DoAsyncStuff()
{
    FooAsync().ContinueWith((res) => { DoSomethingWithInt(res.Result) });
}

Using async , you can write the same code like this: 使用async ,您可以编写相同的代码,如下所示:

void async DoAsyncStuff()
{
    int res = await FooAsync();
    DoSomethingWithInt(res);
}

The result is the same. 结果是一样的。 The await keyword turns the rest of your method into a continuation which gets resumed after FooAsync produces a value. await关键字将方法的其余部分转换为延续,在FooAsync生成值后将继续执行。 It's just like your other code, but easier to read. 它就像你的其他代码一样,但更容易阅读。 *shrug* *耸肩*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM