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?
this
inasync
methods without special thread-locked object is dangerousIf you cannot use
await
, use a code like following.The best solution is to make the calling method
async
and then useawait
, as Bas Brekelmans pointed out.When you make a method
async
, you should change the return type (if it isvoid
, change it toTask
; otherwise, change it fromT
toTask<T>
) and add anAsync
suffix to the method name. If the return type cannot beTask
because it's an event handler, then you can useasync 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.