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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...