从异步方法获取结果

时间:2014-01-02 13:57:53

标签: c# entity-framework asynchronous

我的服务中有这个方法:

public virtual async Task<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 。 如何访问用户类?

2 个答案:

答案 0 :(得分:9)

  • 在没有特殊线程锁定对象的this方法中使用async 危险
  • 如果您无法使用await,请使用以下代码。

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

答案 1 :(得分:9)

最好的解决方案是制作调用方法async,然后使用await,正如Bas Brekelmans指出的那样。

制作方法async时,您应该更改返回类型(如果是void,请将其更改为Task;否则,请将其从T更改为Task<T>)并为方法名称添加Async后缀。如果返回类型不能Task,因为它是一个事件处理程序,那么您可以改为使用async void

如果调用方法是构造函数,则可以从我的博客中使用one of these techniques。调用方法是属性获取器,您可以使用我博客中的one of these techniques

相关问题