This is worse than unnecessary, as you spin the thread to do nothing, and then wait until it finishes doing anything.
The easiest way to do nothing is to do nothing. In the async method, the method will still return the value of Task , but that the Task will be completed already, so something await will start it further to move on to the next thing that it needs to do:
public async virtual Task Save(String path) { if (NewWords.Any()) { await FileManager.WriteDictionary(path, NewWords, true); } }
(In addition, it would be more consistent with the standard if the names SaveAsync and WriteDictionaryAsync were here). If you do not use async (and there is no need, but I understand this example) use Task.CompletedTask :
public virtual Task Save(String path) { if (NewWords.Any()) { return FileManager.WriteDictionary(path, NewWords, true); } return Task.CompletedTask; }
If you are coding an earlier structure than 4.6 and therefore do not have CompletedTask , then Task.Delay(0) is useful as a Delay special cases, a value of 0 to return the completed cached task (in fact, the one returned by CompletedTask ):
public virtual Task Save(String path) { if (NewWords.Any()) { return FileManager.WriteDictionary(path, NewWords, true); } return Task.Delay(0); }
But 4.6 the way is more clear in relation to your intentions, and not depending on the quirk of implementation.
source share