Why doesn't the method containing the asynchronous lambda be Async itself?

For example, whenever I wait for something, the compiler notifies me that the containing method should be Async. Why is the asynchronous lamb not so visible? If ForEach hides it, is there any danger of not returning the Task object, and ForEach is an implicit asynchronous void?

public void SaveSome() { Array.ForEach(Enumerable.Range(0,3).ToArray(), async x => await SaveRep()); } 
+6
source share
2 answers

Asynchronous lambda is just an easy way to create a delegate that is asynchronous. There is nothing to say that the method that contains it should do something asynchronous, and any await expressions in the lambda expression will not force you to support the wait method (unless it expects to complete a task that is supposed to depend on the delegate, of course) .

Basically, a lambda expression expresses some asynchronous code - it does not execute the asynchronous code itself ... so the contained method does not necessarily execute asynchronously.

Yes, the example you provided is the wrong use of async lambdas, but creating an async method will not improve the situation at all, and it will just be misleading.

EDIT: As an alternative way to think about this, consider this source code refactoring:

 public void SaveSome() { Action<int> action = SaveRepAsync; Array.ForEach(Enumerable.Range(0,3).ToArray(), action); } private static async void SaveRepAsync(int x) { await SaveRep(); } 

The SaveSome method has nothing asynchronous in this respect - only the SaveRepAsync method does ... so that the async modifier is required. This is really tiny refactoring of your code (as if compiler refactoring would work efficiently). If you want every method containing an asynchronous lambda to have an async modifier, it is as if said in the above code, SaveSome should also have a modifier ... which does not make sense, IMO.

+9
source

You can use the async async method in the async method, but you can still call them a non-asynchronous method, for example, you do it higher - in this case it’s more like β€œfire” and forget "

+2
source

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


All Articles