2

This is the query:

using (var db = new AppDbContext())
{
    var items = await db.Branches
        .Where(b => b.OrgId == orgId)
        .Select(t => new SelectListItem<int> {Key = t.Id, Value = t.Name})
        .ToListAsync();
    return items;
}

If I replace ToListAsync with ToList, it runs fine, but otherwise it hangs. I suspect some sort of threading issue. The query is called during my viewmodel's InitializeAsync method, which is called from an 'event' in the view:

public override async void OnNavigatedTo(NavigationContext navigationContext)
{
    await InitializeModelAsync(InitModelCts.Token);
}

This is part of the view's implementation of INavigationAware.

ProfK
  • 49,207
  • 121
  • 399
  • 775
  • 2
    This might help: [ToListAsync() does not complete at all](http://stackoverflow.com/a/25899982/6741868) – Keyur PATEL Feb 01 '17 at 06:54
  • Check for ThreadId in both the cases .If they are different then use dispatcher instead – Ramankingdom Feb 01 '17 at 07:13
  • Could this be because `OnNavigatedTo` isn't really `async` from the beginning? I found [this blog](https://invokeit.wordpress.com/2012/10/15/async-await-and-onnavigatedto-wpdev-win8dev/). – smoksnes Feb 01 '17 at 10:07

1 Answers1

1

Does it work if you don't capture the context by calling the ConfigureAwait method?:

using (var db = new AppDbContext())
{
    var items = await db.Branches
        .Where(b => b.OrgId == orgId)
        .Select(t => new SelectListItem<int> { Key = t.Id, Value = t.Name })
        .ToListAsync().ConfigureAwait(false);
    return items;
}

Also note the initial Entity Framework setup is not really asynchronous:

EF6 ToListAsync freezes Winforms

...so you might want to offload the entire query and context creation to a background thread:

await Task.Run(()=> 
{
    using (var db = new AppDbContext())
    {
        var items = db.Branches
                    .Where(b => b.OrgId == orgId)
                    .Select(t => new SelectListItem<int> { Key = t.Id, Value = t.Name })
                    .ToList();
        return items;
    }
});
Community
  • 1
  • 1
mm8
  • 163,881
  • 10
  • 57
  • 88
  • I solved it using `SynchronizationContext.Post`, with a delegate that awaits the query, as is with `ToListAsync`. – ProfK Feb 01 '17 at 15:35