Created
October 27, 2017 14:38
-
-
Save priyankadavle/6f149850ab55bf95f17c56ea5c332bca to your computer and use it in GitHub Desktop.
Suppress warning CS1998: This async method lacks 'await'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
I've got an interface with some async functions. | |
Methods returning Task, I believe. async is an implementation detail, so it can't be applied to interface methods. | |
Some of the classes that implements the interface does not have anything to await, and some might just throw. | |
In these cases, you can take advantage of the fact that async is an implementation detail. | |
If you have nothing to await, then you can just return Task.FromResult: | |
public Task<int> Success() // note: no "async" | |
{ | |
... // non-awaiting code | |
int result = ...; | |
return Task.FromResult(result); | |
} | |
In the case of throwing NotImplementedException, the procedure is a bit more wordy: | |
public Task<int> Fail() // note: no "async" | |
{ | |
var tcs = new TaskCompletionSource<int>(); | |
tcs.SetException(new NotImplementedException()); | |
return tcs.Task; | |
} | |
If you have a lot of methods throwing NotImplementedException (which itself may indicate that some design-level refactoring would be good), then you could wrap up the wordiness into a helper class: | |
public static class TaskConstants<TResult> | |
{ | |
static TaskConstants() | |
{ | |
var tcs = new TaskCompletionSource<TResult>(); | |
tcs.SetException(new NotImplementedException()); | |
NotImplemented = tcs.Task; | |
} | |
public static Task<TResult> NotImplemented { get; private set; } | |
} | |
public Task<int> Fail() // note: no "async" | |
{ | |
return TaskConstants<int>.NotImplemented; | |
} | |
The helper class also reduces garbage that the GC would otherwise have to collect, since each method with the same return type can share its Task and NotImplementedException objects. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment