我在我的代码中经常使用 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
。
关于c# - 不直接返回任务时最恰本地使用 Async/Await?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43014376/