Get result from async method

asynchronous c# entity-framework

Question

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?

1
12
1/2/2014 1:57:53 PM

Accepted Answer

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.

12
1/2/2014 2:13:31 PM

Popular Answer

  • Using this in async methods without special thread-locked object is dangerous
  • If you cannot use await, use a code like following.

    Task<User> task = TaskFindByIdAsync();
    
    task.Wait(); //Blocks thread and waits until task is completed
    
    User resultUser = task.Result;
    


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow