c# - 不直接返回任务时最恰本地使用 Async/Await?

标签 c# asynchronous async-await task-parallel-library

我在我的代码中经常使用 async await,但我发现我可能没有按照我应该做的那样恰本地使用它。

我正在寻找确认我对处理异步/等待方法的最佳方式的理解,这些方法执行多项操作并且不直接返回任务结果。

当我只想直接返回任务结果时,我通常会这样做。

    //basic - 1 thing to do - directly return task
    public Task<string> ReturningATask(string key)
    {
        return _cache.GetStringAsync(key);
    }

但是,当我想在返回之前用任务的值一些事情时,我习惯于将方法异步化并等待其中的任务。

    //More than a single operation going on.
    //In this case I want to just return a bool indicating whether or not the key exists.
    public async Task<bool> ReturningABool(string key)
    {
        string foundValue = await _cache.GetStringAsync(key);

        if (string.IsNullOrEmpty(foundValue))
        {
            return false;
        }
        else
        {
            return true;
        }
    }

我突然想到 ContinueWith 可能是处理这个问题的更合适的方法。

下面的例子是普遍接受的处理方式吗? 我想到“永远不要使用 task.Result,因为它是阻塞的”,但是使用 ContinueWith,任务已经完成,所以没有阻塞对吧?

    //The more correct way?        
    public Task<bool> ReturningATaskBool(string key)
    {
        return _cache.GetStringAsync(key)
            .ContinueWith(x =>
            {
                if (string.IsNullOrEmpty(x.Result))
                {
                    return false;
                }
                else
                {
                    return true;
                }
            });
    }

谢谢。

最佳答案

ContinueWith 是一种危险的低级 API。具体来说,它:

  • 不理解异步延续。
  • 使用当前 TaskScheduler(不是默认 TaskScheduler)作为其的默认值TaskScheduler 参数。
  • 没有适当的延续标志默认行为(例如,DenyChildAttach)。

await 没有这些问题。您应该使用 await 而不是 ContinueWith

See my blog for an exhaustive (exhausting?) discussion .

关于c# - 不直接返回任务时最恰本地使用 Async/Await?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43014376/

相关文章:

c# - 返回新 Task<HttpResponseMessage> 的 IActionFilter 从不返回

c# - 有关用于过滤集合的 LINQ 查询的建议

c# - 等效于 C# 中的 PostMessage 以使用 MVVM 与主线程同步?

javascript - 如何使用对象方法作为回调来修改JavaScript中的对象属性

javascript - CasperJS 在 for 循环内继续

c# - 在不抛出异常的情况下测试字符串是否为 guid?

powershell - 是否可以异步调用 powershell cmdlet?

asynchronous - async/await - 在 future() 之前不等待 - Dart

c# - 您可以使用 Task.Run 将受 CPU 限制的工作移至后台线程

asynchronous - Future 和异步行为不一样,我不明白