【问题标题】:Does a pass-through async method really need the await/async pattern? [duplicate]传递异步方法真的需要等待/异步模式吗? [复制]
【发布时间】:2017-07-04 13:40:33
【问题描述】:

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

//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 需要/应该有 async/await,而不是简单地调用:

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

在消费者中,这仍然会被等待,就像这样,不管:

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

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

【问题讨论】:

    标签: c# asynchronous async-await c#-5.0


    【解决方案1】:

    这取决于。特别是如果Convert.ToInt32 throws,异常行为是不同的。

    我有一个完整的blog post on the subject,但总的来说,我会在这里使用async/await,因为异常会放在返回的任务上。否则直接抛出异常。

    直接抛出异常仅适用于前置条件异常(即,传递无法转换为 int 的 double 是违反 API 的)。即使这样(对于前置条件异常),您也可以选择直接抛出异常或将它们放在返回的任务上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      相关资源
      最近更新 更多