如果有条件地执行Task,异步方法应该怎么做? [英] What should an async method do if a Task is conditionally executed?

查看:70
本文介绍了如果有条件地执行Task,异步方法应该怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个等待任务的方法.此方法还返回一个Task.例如:

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(() => { });
}

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?

推荐答案

这比不必要的要糟,因为您正在旋转线程以不执行任何操作,然后等待其完成不执行操作.

It's worse than unnecessary, as you're spinning up a thread to do nothing and then waiting until after its finished doing nothing.

什么都不做的最简单方法就是什么都不做.在async方法中,该方法仍将返回Task,但是Task将已经完成,因此进一步进行await的操作将直接进入它需要做的下一件事:

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);
    }
}

(此外,如果SaveAsyncWriteDictionaryAsync是此处的方法名称,则将更符合约定). 如果不使用async(并且不需要在这里,但我理解这是一个示例),请使用Task.CompletedTask:

(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;
}

如果您是针对4.6之前的框架编写的,因此没有CompletedTask可用,则Task.Delay(0)很有用,因为Delay特殊情况下,值0可以返回缓存的已完成任务(实际上,与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);
}

但是4.6方式对于您的意图更清晰,而不是取决于实现的怪癖.

But the 4.6 way is clearer as to your intent, rather than depending on a quirk of implementation.

这篇关于如果有条件地执行Task,异步方法应该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆