C# Error CS1994 – The ‘async’ modifier can only be used in methods that have a body.

C# Error

CS1994 – The ‘async’ modifier can only be used in methods that have a body.

Reason for the Error & Solution

The ‘async’ modifier can only be used in methods that have a body.

Example

The following sample generates CS1994:

interface IInterface
{
    async void F();
}

To correct this error

A non-concrete method declaration in an interface declaration has no method body. In order to support the async modifier, the compiler subsumes the method body logic in a state machine. Without a method body, the compiler cannot emit this state machine. In addition, the logic of a method body must contain an await operator to signify a continuation the state machine must manage. Without that await operator, a state machine has nothing to manage.

In the case of a non-concrete method, if deferring the implementation of a method body to a class that implements the interface, simply removing the async modifier will correct the error:

interface IInterface
{
    void F();
}

Alternatively, a concrete default method (introduced in C# 8.0) could be declared within the interface:

interface IInterface
{
    async void F()
    {
        await Task.Run(() =>
        {
            /* do something useful*/
        });
    }
}

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...