c# async method and return await(c# async方法并返回await)
问题描述
一个简单的问题.我找到了一些具有这种逻辑"和架构"的方法.
one simple question. I found some methods with this "logic" and "architecture".
public async Task<T> FindAsync(params object[] keys)
{
return await this.context.FindAsync(keys);
}
一条带有等待的指令.由于该方法是异步的,因此您必须这样做(否则会发生编译器错误).恕我直言,我找不到为什么要使用这种模式,因为如果方法是异步的,您可能希望并行执行不同的任务.如果您使用 await 关键字同步执行,您会使该方法接近同步,并且您会失去 .net 的托管线程池机制的所有性能增益.你有什么意见?我错了吗?
One single instruction with its await. Since the method is async you have to do this (otherwise compiler errors occur). IMHO i can't find why you should use this pattern because if the method is async you probably want to perform different tasks in parallel. If you sync the execution with the await keyword you make the method close to sync and you loose all the performance gain of the managed thread pool mechanism of .net. What is your opinion? I'm in wrong?
推荐答案
如果你这样调用这个方法:
If you're calling this method like this:
await FindAsync(); // this method waits for the task to complete
那么在这个方法里面返回await就没有意义了,你可以改成:
Then it doesn't make any sense to return await inside this method, you can just change it to:
public Task<T> FindAsync(params object[] keys)
{
return this.context.FindAsync(keys); // Start and return the task
}
然后调用者等待任务完成.
Then the caller awaits the task to Complete.
这篇关于c# async方法并返回await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c# async方法并返回await


基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01