When implementing against an interface (because of mocking, remoting or similiar) using the await keyword and having an interface with methods returning Task<> :
interface IFoo { Task<BigInteger> CalculateFaculty(int value); }
the compiler comes up with an error:
The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'
Which is a bit unusual considering the return type is "Task". This problem is kind of frustrating and forces me to "fall back" using continuation style or providing an extra proxy around this interface (and therefore for almost every interface which is not really feasible for me)
Does anyone have a good idea on how to solve this?
Interfaces can't use async in a method declaration, simply because there is no need. If an interface requires that a method returns Task , the implementation may choose to use async , but whether it does or not is a choice for the implementing method.
You read the 'await' keyword as "start this long running task, then return control to the calling method". Once the long-running task is done, then it executes the code after it. The code after the await is similar to what used to be CallBack methods.
The await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes. When the asynchronous operation completes, the await operator returns the result of the operation, if any.
The message is not about the interface, but about the calling method. You need to mark the method containing the await
keyword with the async
modifier:
public interface IFoo { Task<int> AwaitableMethod(); } class Bar { static async Task AsyncMethod() // marked as async! { IFoo x; await x.AwaitableMethod(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With