传递异步方法是否真的需要等待/异步模式? [英] Does a pass-through async method really need the await/async pattern?

查看:156
本文介绍了传递异步方法是否真的需要等待/异步模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个方法可以立即调用另一个异步方法或类似方法:

Let's say I have an method that calls another async method immediately or similar:

//Main method
public async Task<int> Foo1( int x )
{
     var result = await DoingSomethingAsync(x );
     return DoSomethingElse(result );
}  
//other method
public async Task<int> Foo2( Double double )
{
     return await Foo1( Convert.ToInt32(double ) );
}  

与简单的调用相反, Foo2 是否需要/应该具有异步/等待的特定原因?

Is there any specific reason that Foo2 needs/should have async/await, as opposed to simply calling:

//other method
public Task<int> Foo3( Double double )
{
     return Foo1( Convert.ToInt32( double ) );
}  

在消费者中,无论如何,这仍将等待,

In a consumer, this would still be awaited, likeso, regardless of:

int x = await Foo1(1);
int x = await Foo2(1D);
int x = await Foo3(1D);

所有这些语句都将编译.编译器会为两种不同的方法生成不同的IL吗?

All those statements will compile. Will the compiler generate different IL for the two different methods?

推荐答案

这要视情况而定.特别是,如果 Convert.ToInt32 抛出,则异常行为会有所不同.

It depends. In particular, the exception behavior is different if Convert.ToInt32 throws.

我有整篇关于该主题的博客帖子,但总而言之,我将在此处使用 async / await ,因为异常将放置在返回的任务上.否则,将直接引发异常.

I have a whole blog post on the subject, but in summary, I would use async/await here because the exception would be placed on the returned task. Otherwise, the exception would be thrown directly.

直接引发异常仅适用于先决条件异常(即,传递一个不能转换为int的double违反API).即使这样(对于前提条件异常),您也可以选择直接引发异常或将其放置在返回的任务上.

Throwing exceptions directly is only acceptable for precondition exceptions (i.e., it's a violation of the API to pass a double that can't be converted to an int). And even then (for precondition exceptions) you can choose to either throw exceptions directly or place them on the returned task.

这篇关于传递异步方法是否真的需要等待/异步模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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