Is it possible to make a function that will throw an error if it does not have an await keyword next to it? I am not using this for anything, I am just curious, and I think I can see that it might have it's uses if the data processed greatly affects the operation of the program.
Asked
Active
Viewed 713 times
-2
-
Not sure you could force it, you could maybe add "4014" to the list of "Treat warnings as errors" in project properties. – DavidG Jul 06 '18 at 10:10
-
What if your caller wanted to [elide async and await](https://stackoverflow.com/q/50464355/9695604)? It is a very bad idea, don't make assumptions about your caller. – bommelding Jul 06 '18 at 10:12
-
maybe should you put some code? -.- did you try it at least once or are you waiting for ready solution? – Presto Jul 06 '18 at 10:20
-
From what I can find online the closest thing is detecting whether a task has been awaited. Obviously if you detect it you could create and throw your own exception but, the problem is you can only detect this once it has already done the asynchronous operation. I am wondering if you could block the call (with a compiler error) or throw an exception in advance. – Pharez Jul 06 '18 at 10:39
2 Answers
0
There's not necessarily a good way to do that. Elevating the warning code to an error is one option. But if you're only concerned with async
functions that return a result, i.e. Task<T>
, then there is a possibilty of a compile time check.
For Example:
public class ForceAwait
{
public Task<int> MethodAsync() => Task.FromResult(1);
public Task Caller_Does_Not_Compile()
{
int result = MethodAsync();
return Task.CompletedTask;
}
public async Task Caller_Compiles()
{
int result = await MethodAsync();
}
}
By explicitly typing the result to T
instead of using var
then he compiler can provide an error if you try to assign a Task<T>
to a variable of type T
. Of course this is only a trick/hack that doesn't apply to a method returning Task
.

JSteward
- 6,833
- 2
- 21
- 30
0
Agreed with DavidG. Try to set compiler warning level to 4 and enable "Treat warnings as errors" for your project. Do it for Debug, Release and all configurations.

Sergei Zinovyev
- 1,238
- 14
- 14