Recently, I have rewritten the code to async + await. In some cases, I found that the asynchronous method needs to be called in finally, but the compiler does not allow the await keyword to appear in cache and finally... However, using wait () or result may lead to some other strange problems (deadlock, aggresponexception ...)
Therefore, you need to find a finally-like effect and allow the use of async... await. After thinking about it, isn't it actually continuewith!
You can use the following method for try... finally without return values:
Public Static AsyncTask withfinally (ThisTask trycode, func <task, task>Finallycode ){Await AwaitTrycode. continuewith (finallycode );}
Why is it await? This question is about the returned value of continuewith. continuewith (Action <task>) returns the task, so only one await is required. Continuewith (func <task, tresult> returns the task <tresult>. Here, tresult is the task. Therefore, the return value is the task <task>, await task <task>, the result is another task. It is clear that the task has not been completed, and then wait for the task to have two await instances.
Here is an example:
Async Task sample (){ // Do something... Await Trypart (). withfinally ( Async Task => { // Do something... Await Asynccallinfinally (); // Do something... }); // Do something... } Task trypart (){ // ... } Task asynccallinfinally (){ // ... }
But if there is a trypart return value? Therefore, we need such a overload:
Public Static AsyncTask <tresult> withfinally <tresult> (ThisTask <tresult> trycode, func <task <tresult>, task>Finallycode ){Await AwaitTrycode. continuewith (finallycode );Return AwaitTrycode ;}
Here we assume that the finally part does not modify the try part's return value. In addition to the previous await in the code, a return await trycode is added. Why should we use await trycode instead of trycode. Result?
Do you still remember the strange issues mentioned above? Although it is impossible to use the result here to have a deadlock (the previous await can ensure that finallycode is executed completely, and finallycode is run after trycode is completed, so trycode must be completed at this time ), however, when an error occurs, the two are different. Await trycode will throw an exception in the original trycode, while trycode. result will throw aggresponexception.
Finally, you should be careful with a trap in finallycode. Do not read trycode. Result at will. It may be an exception!