从异步方法获取结果
我的服务中有这个方法:
public virtual async Task FindByIdAsync(string userId) { this.ThrowIfDisposed(); if (userId == null) { throw new ArgumentNullException("userId"); } return await this.repository.FindByIdAsync(userId); }
然后在视图中我有这个代码:
using (var service = new UserService(new CompanyService(), User.Identity.GetUserId())) { var user = service.FindByIdAsync(id); }
但用户是任务而不是用户 。 我尝试添加等待服务调用,但除非当前方法是异步,否则我不能使用await 。 如何访问User类?
Bas Brekelmans指出,最好的解决方案是使调用方法async
,然后使用await
。
当您创建方法async
,您应该更改返回类型(如果它是void
,将其更改为Task
;否则,将其从T
更改为Task
)并将Async
后缀添加到方法名称。 如果返回类型不能是Task
因为它是一个事件处理程序,那么您可以使用async void
。
如果调用方法是构造函数,则可以从我的博客中使用这些技术之一 。 它的调用方法是属性getter,你可以从我的博客中使用这些技术之一 。
- 在没有特殊线程锁定对象的
async
方法中使用this
是危险的 -
如果您不能使用
await
,请使用如下代码。Task
task = TaskFindByIdAsync(); task.Wait(); //Blocks thread and waits until task is completed User resultUser = task.Result;