C# Error CS4008 – Cannot await ‘void’

C# Error

CS4008 – Cannot await ‘void’

Reason for the Error & Solution

Cannot await ‘void’

Example

The following sample generates CS4008:

// CS4008.cs (7,33)

using System.Threading.Tasks;

class Test
{
    public async void goo()
    {
        await Task.Factory.StartNew(() => { });
    }

    public async void bar()
    {
        await goo();
    }

    public static void Main() { }
}

To correct this error

Although this error can be corrected by changing the signature of goo:

    public async Task goo()
    {
        await Task.Factory.StartNew(() => { });
    }

Simply adding Task to the method’s signature needlessly perpetuates a compiler-created state machine when it is not needed. The goo method does not require an await, nor does it need to be asynchronous. Instead, consider simply returning the Task created by Task.Factory:

    public Task goo()
    {
        return Task.Factory.StartNew(() => { });
    }