c# async method and return await

2019-03-01 11:02发布

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);
}

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?

1条回答
放荡不羁爱自由
2楼-- · 2019-03-01 11:06

If you're calling this method like this:

await FindAsync(); // this method waits for the task to complete

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.

查看更多
登录 后发表回答