【发布时间】:2017-08-18 06:28:45
【问题描述】:
我在我的代码中经常使用 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;
}
});
}
谢谢。
【问题讨论】:
-
你做用异步/等待返回任务。
-
是的,对不起,你说的很对,我说错了。我想我搞砸了我的第二个代码示例,因为我通常所做的只是将其设为 async bool,而不是 async Task
当然不会返回任务。编辑问题以删除该位。 -
你可以做
return !string.IsNullOrEmpty(x.Result)
标签: c# asynchronous async-await task-parallel-library