如果我不在异步方法中使用 Task 怎么办?
嗯,这是设计使然。
如果你想使用async,你有一组有效返回类型的限制*:
void
Task
Task<T>
task-like type
IAsyncEnumerable<T>
IAsyncEnumerator<T>
* 此处省略 lambda 和异常方法。
其他的都是无效的。而void 被认为是不好的做法。
例如:
public async int DoIt()
会导致这个错误:
错误 CS1983 异步方法的返回类型必须是 void、Task、Task、类似任务的类型、IAsyncEnumerable 或 IAsyncEnumerator
另外,async 修饰符本身并没有多大作用。我认为这是一个普遍的误解。
它不会使您的代码“异步”它是任务的组合,与 await 关键字一起允许您异步执行任务但随后以后续方式继续 - 这就是 @987654333 @ 构造用于。
我强烈建议您阅读先生。 Cleary 关于该主题的博客:
https://blog.stephencleary.com/2012/02/async-and-await.html
正如他所说:
“async”关键字在该方法中启用“await”关键字并更改方法结果的处理方式。这就是 async 关键字的全部作用!它不会在线程池线程上运行此方法,也不会执行任何其他类型的魔法。 async 关键字只启用 await 关键字(并管理方法结果)。
正如评论:如果你想使用 await,你只需要 async。只有在异步方法之后需要执行某些操作时才使用 await。
另外:任务可能是异步的,但并非必须如此。为简单起见,让我们在以下示例中假设它们是:
一些例子:
// no async, yet possibly asynchronous.
// Task can be returned directly, it's still asynchronous.
public Task<int> ProcessData()
{
return _dbContext.SaveChangesAsync();
}
// no async, yet possibly asynchronous.
// returning the task directly
public async Task<int> ProcessData()
{
var result = await _dbContext.SaveChangesAsync();
//await needed if you want to continue here after the task is completed.
if (result < 1)
throw new ValidationException("should be higher then 1");
return result;
}
以下 2 个示例未添加任何内容和/或无效:
// returning the task directly
public Task<int> ProcessData()
{
//ERROR: missing async keyword
var result = await _dbContext.SaveChangesAsync();
return result;
}
// returning the task directly
public async Task<int> ProcessData() //WARNING: missing await keyword
{
//WARNING: missing await keyword
return _dbContext.SaveChangesAsync();
}