What should the async method do if the task is executed conditionally?

Suppose I have a method waiting for a task. This method also returns the task. For instance:

public async virtual Task Save(String path) { if (NewWords.Any()) { await FileManager.WriteDictionary(path, NewWords, true); } else await Task.Run(() => { }); } 

Does it

 else await Task.Run(() => { }); 

is needed here or can i leave it? Is there any difference if it is present / absent? Maybe there is some other approach to this that I should take?

+5
source share
2 answers

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.

+4
source

It's not obligatory. async is required only if at least one await . Everything inside the method is executed synchronously, with the exception of await , and that after it.

+5
source

Source: https://habr.com/ru/post/1246697/


All Articles