从异步方法获取结果 [英] Get result from async method
问题描述
public virtual async任务< User> 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);
}
但用户是任务,而不是用户即可。我尝试向服务调用添加等待,但除非当前方法是异步,否则我无法使用等待。
如何访问用户类?
最好的解决方案是调用方法 async
,然后使用 await
,如Bas Brekelmans指出的。
当您进行方法 async
时,您应该更改返回类型(如果是 void
,将其更改为任务
;否则将其从 T
更改为任务< T> / code>),并为方法名称添加一个
Async
后缀。如果返回类型不能 任务
,因为它是一个事件处理程序,那么您可以使用 async void
代替。
如果调用方法是构造函数,可以使用这些技术之一从我的博客。调用方法是属性getter,您可以使用其中一个技巧。
I have this method in my service:
public virtual async Task<User> FindByIdAsync(string userId)
{
this.ThrowIfDisposed();
if (userId == null)
{
throw new ArgumentNullException("userId");
}
return await this.repository.FindByIdAsync(userId);
}
and then in a view I have this code:
using (var service = new UserService(new CompanyService(), User.Identity.GetUserId()))
{
var user = service.FindByIdAsync(id);
}
but the user is the Task and not the User. I tried adding await to the service call, but I can't use await unless the current method is async. How can I access the User class?
The best solution is to make the calling method async
and then use await
, as Bas Brekelmans pointed out.
When you make a method async
, you should change the return type (if it is void
, change it to Task
; otherwise, change it from T
to Task<T>
) and add an Async
suffix to the method name. If the return type cannot be Task
because it's an event handler, then you can use async void
instead.
If the calling method is a constructor, you can use one of these techniques from my blog. It the calling method is a property getter, you can use one of these techniques from my blog.
这篇关于从异步方法获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!