gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:23:22 24 4
gpt4 key购买 nike

我在我的代码中经常使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com