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(() => { });
    }

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...