C# .net 4.5 async delegate

This does not throw compile error, but why?

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

Action<object> myAnonActionDelegate = DoSomething;

Shouldn't "DoSomething" have a signature of type Func<object,Task> as opposed to Action? In fact "DoSomething" is not be assignable to Func<object,Task> delegate.

The question is why? Is my understanding about async keyword off?


Shouldn't "DoSomething" have a signature of type Func<object,Task> as opposed to Action?

No - the method doesn't return anything. Look at the declaration - it's void, not Task. The async part is just for the compiler's benefit (and humans reading it) - it's not really part of the signature of the method. An async method must return either void, Task, or Task<T> - but the return type of the method really is just what you declare it to be. The compiler doesn't turn your void into Task magically.

Now you could write the exact same method body and declare the method as:

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

at which point you would need to use Func<object, Task> - but that's a different method declaration.

I would strongly advise you to use the form returning Task unless you're using an async method to subscribe to an event - you might as well allow callers to observe your method's progress, failure etc.

Need Your Help

PHP, Return everything to the left, strrchr()?


The following code returns everything to right of the last occurrence of a dash:

Creating lock so two users don't create account with the same username

javascript node.js concurrency

I am using the Express server with Node.js and am concerned about concurrency and preventing users from creating accounts with the same username at the same time. From my underatanding, despite the...