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


基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01