c# async方法并返回await [英] c# async method and return await

查看:27
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆