C#异步方法并返回等待 [英] c# async method and return await

查看:1407
本文介绍了C#异步方法并返回等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题.我发现了一些使用这种逻辑"和体系结构"的方法.

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#异步方法并返回等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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