Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework hangs when using async calls

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?

CONTROLLER

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);
}

SERVICE

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

REPOSITORY

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

UPDATE:

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"

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);
}
like image 416
devfunkd Avatar asked Feb 13 '23 16:02

devfunkd


1 Answers

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);
}

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.

like image 101
Stephen Cleary Avatar answered Feb 15 '23 07:02

Stephen Cleary