异步等待和重载方法

异步等待和重载方法

本文介绍了.NET 4.5 异步等待和重载方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个异步方法:

public async Task<UserLoginExResult> LoginExAsync(CustomTable exRequest, string language, bool throwEx = true)
{
    UserLoginExResult result = await UserService.LoginExAsync(UserGroup, language, TimezoneOffset, GetDeviceInfo(), GetLoginProperties(), exRequest);

    ProcessLoginResult(result, false, throwEx);

    return result;
}

还有一个重载:

public Task<UserLoginExResult> LoginExAsync(CustomTable exRequest, bool throwEx = true)
{
    return LoginExAsync(exRequest, Language.ID, throwEx);
}

我不确定是否应该将重载的(参数较少的)标记为 async 并使用 await?我想我不应该但是你能告诉我如果我这样做会发生什么吗?我在这里很迷茫,不确定它会等待什么 Task ?它会创建一个额外的 Task 还是 await 不会创建一个新的 Task?

I'm not sure if I should mark the overloaded one (the one with fewer parameters) as async and use await? I guess I should not but can you tell me what whould happen if I would do that? I'm quite lost in here and not really sure what Task it would wait for? Would it create an extra Task or await doesn't create a new Task?

推荐答案

不,当异步方法只是要包装和解开现有方法时,使用它几乎没有什么好处.这里有一个正常"的方法,委托给真正的"异步方法就好了.

No, there's little benefit in using an async method when it's just going to wrap and unwrap an existing one. It's fine to just have a "normal" method here, delegating to the "real" async method.

(它们不完全相同 - 例如,如果 UserService.LoginExAsync 方法抛出异常而不是返回失败的任务,async/await 版本只会返回一个失败的任务,而另一个版本会立即抛出.)

(They're not quite the same - for example, if the UserService.LoginExAsync method throws an exception rather than returning a failed task, the async/await version will just return a failed task, whereas the other version will also throw immediately.)

这篇关于.NET 4.5 异步等待和重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 08:28