It's worse than unnecessary, as you're spinning up a thread to do nothing and then waiting until after its finished doing nothing.
The simplest way to do nothing, is to do nothing. In an async
method the method will still have returned a Task
, but that Task
will be completed already, so something await
ing it further up will get straight onto the next thing it needs to do:
public async virtual Task Save(String path)
{
if (NewWords.Any())
{
await FileManager.WriteDictionary(path, NewWords, true);
}
}
(Also, it would be more in line with convention if SaveAsync
and WriteDictionaryAsync
were the method names here).
If not using async
(and there's no need to here, but I understand it's an 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 against an earlier framework than 4.6 and therefore don't have CompletedTask
available, then Task.Delay(0)
is useful as Delay
special cases the value 0
to return a cached completed task (in fact, the same one that CompletedTask
returns):
public virtual Task Save(String path)
{
if (NewWords.Any())
{
return FileManager.WriteDictionary(path, NewWords, true);
}
return Task.Delay(0);
}
But the 4.6 way is clearer as to your intent, rather than depending on a quirk of implementation.