Does the asynchronous end-to-end access method really need a wait / async pattern?

Let's say I have a method that calls another asynchronous method immediately or similarly:

//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 ) ); } 

Is there any specific reason Foo2 needs / should have async / wait, and not just a call:

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

The consumer would still be expected, in addition, regardless of:

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

All of these statements will be compiled. Will the compiler generate different ILs for two different methods?

+5
source share
1 answer

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

I have a whole blog entry on the topic , but in the end I would use async / await here because the exception would be put in the returned task. Otherwise, the exception will be thrown directly.

Exception exceptions are only for permissible exceptions for the premise (i.e., this is a violation of the API for passing a double that cannot be converted to int). And even then (for exceptions to the preconditions) you can choose to throw exceptions directly, or put them in the returned task.

+6
source

Source: https://habr.com/ru/post/1264264/


All Articles