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*/
});
}
}