Async lambda expressions in VB.NET

async-await, lambda, vb.net

Solution

VB.NET `Sub` is equivalent to C# returning `void`. There's a difference between `async void Foo() {}` and `async Task Foo() {}`, and your VB.NET is doing the former, while you want the latter. As you mention, `Async Function` makes it work, because then it actually does the latter.

Edit: some more details:

C#:

async void Foo() { }

async Task Bar() { }

void Baz()
{
    object dummy;
    dummy = (Action) Foo; // OK
    dummy = (Func<Task>) Foo; // error
    dummy = (Action) Bar; // error
    dummy = (Func<Task>) Bar; // OK
}

However, this gets a bit more confusing when delegates are used, because the delegate equivalents of `Foo` and `Bar` look the same: `async () => { }`.

The only difference is that in VB.NET, the delegates do not look the same, because the `Sub` or `Function` keyword remains part of the syntax there.

Problem

Async `Sub` like this: ``` Dim f As Func(Of Task) = Async Sub() End Sub ``` Produces compiler error: error BC36670: Nested sub does not have a signature that is compatible with delegate 'System.Func(Of System.Threading.Tasks.Task)'. Equivalent C# code compiles fine: ``` Func<Task> f = async () => { }; ``` Rewriting `Async Sub` into `Async Function` make code works. Why does `Async Sub()` is not convertible to delegate types with return value of type `Task`?

Original source