C # .net 4.5 async delegate

This does not throw a compilation error, but why?

public async void DoSomething(object arg){ ... } Action<object> myAnonActionDelegate = DoSomething; 

Should " DoSomething " have a signature like Func<object,Task> , and not Action? In fact, “ DoSomething ” cannot be assigned to the delegate Func<object,Task> .

The question is why? Is my understanding of the async keyword disabled?

+4
source share
1 answer

Should "DoSomething" have a signature like Func<object,Task> , and not Action?

No - the method returns nothing. Look at the ad - it's void , not Task . The async part is only for getting the compiler (and the people reading it) - this is not part of the method signature. The async method should return either void , Task , or Task<T> , but the type of the returned method is really what you are declaring. The compiler does not turn your void into Task magically.

Now you can write the same method tag and declare the method as:

 public async Task DoSomething(object arg){ ... } 

at this point you will need to use Func<object, Task> - but this is another method declaration.

I would highly recommend using a form that returns Task if you do not use the asynchronous event subscription method - you can also allow callers to monitor your method, failure, etc.

+6
source

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


All Articles