使用异步调用时,实体框架挂起 [英] Entity Framework hangs when using async calls

查看:48
本文介绍了使用异步调用时,实体框架挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用async并不陌生,这似乎使我难以理解是什么原因或问题所在,当我尝试加载网页时,async调用似乎挂起并且该页面从未加载.我的实现在这里错误吗?

I am new to using async and this seems to elude me on what the cause or issue is, when I attempt to load the webpage the async call seems to hang and the page is never loaded. Is my implementation wrong here?

控制器

public ActionResult Index()
{

    var model = _partyAddOnService.Get().Result.Select(x => new AddOnModel()
    {
        Id = x.Id,
        AddOnType = x.AddOnType,
        Description = x.Description,
        Name = x.Name,
        Price = x.Price
    });

    return View(model);
}

服务

public async Task<IEnumerable<AddOn>> Get()
{
    return await _repository.GetAsync();
}

存储库

public async Task<IEnumerable<T>> GetAsync()
{
    return await Context.Set<T>().ToListAsync();
}

更新:

我也尝试过,但仍然挂起...

I tried this as well and it still hangs...

public ActionResult Index()
{

    var model = _partyAddOnService.Get();
    return View();
}

* 调试并查看任务状态时,显示正在等待激活"

* When debugging and looking at the Task status it says "Waiting for activation"

还尝试使用本文建议的ConfigureAwait方法.(请参阅下面的James评论)

Also tried using the ConfigureAwait method as the article suggested. (see James comment below)

public async Task<IEnumerable<AddOn>> Get()
{
    return await _repository.GetAsync().ConfigureAwait(false);
}

推荐答案

为防止死锁,只需完全使用 async .您已经在服务和存储库中使用了它,因此只需将其添加到您的控制器中即可:

To prevent deadlocks, just use async all the way up. You're already using it in your service and repository, so just add it to your controller:

public async Task<ActionResult> Index()
{
  var model = (await _partyAddOnService.Get()).Select(x => new AddOnModel()
  {
    Id = x.Id,
    AddOnType = x.AddOnType,
    Description = x.Description,
    Name = x.Name,
    Price = x.Price
  });

  return View(model);
}

我还建议您将异步方法更改为以 Async 结尾,以遵循

I also recommend that you change your async methods to end in Async, to follow the Task-based Asynchronous Pattern. I.e., Get should be GetAsync.

这篇关于使用异步调用时,实体框架挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆