What should an async method do if a Task is conditionally executed?

落爺英雄遲暮 提交于 2019-12-07 06:59:13

问题


Suppose I have a method that awaits a Task. This method also returns a Task. For example:

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

Is the

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

necessary here or am I free to leave it? Is there any difference if it is present/absent? Maybe there is some other approach to this I should take?


回答1:


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 awaiting 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.




回答2:


It's not neccesary. The async is only needed if at least one await is used. Everything inside the method is executed synchronously except for the await and what does after it.



来源:https://stackoverflow.com/questions/36499297/what-should-an-async-method-do-if-a-task-is-conditionally-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!