3

I'm following a walkthrough on how to combine EntityFramework with WPF. I decided to play around with async/await while I'm at it, because I've never really had a chance to use it before (we've just moved to VS2013/.NET 4.5 from VS2010/.NET 4.0). Getting the save button handler to be async was a breeze, and the UI remained responsive (I can drag the window around) while SaveChangesAsync() is awaited. In the window load handler, however, I ran into a small snag.

    private async void Window_Loaded(object sender, RoutedEventArgs e)
    {
        EnterBusyState();
        var categoryViewSource = (CollectionViewSource)FindResource("categoryViewSource");
        _context = await Task.Run(() => new Context());
        await Task.Run(() => _context.Categories.Load());
        //await _context.Categories.LoadAsync();
        categoryViewSource.Source = _context.Categories.Local;
        LeaveBusyState();
    }

When I use the first way of loading _context.Categories, the UI remains responsive, but when I substitute with the commented-out line below, the UI freezes for a brief moment while the entities load. Does anyone have an explanation on why the former works while the latter doesn't? It's not a big deal, it's just bugging me that the second line doesn't work when, at least according to what I've researched about async/await so far, it should.

svick
  • 236,525
  • 50
  • 385
  • 514
kinghajj
  • 253
  • 1
  • 8

1 Answers1

7

Even if a method ends with *Async or return a Task does not mean it is fully async or async at all...

Example:

public Task FooAsync()
{
    Thread.Sleep(10000); // This blocks the calling thread
    return Task.FromResult(true);
}

Usage (looks like an async call):

await FooAsync();

The sample method is completely synchronous even though it returns a task... You need to check the implementation of LoadAsync and ensure that nothing blocks.

When using Task.Run everything in the lambda is executed async on the thread pool... (or at least not blocking the calling thread).

Rico Suter
  • 11,548
  • 6
  • 67
  • 93
  • As written, when compiled `FooAsync()` will generate warning [CS1998](http://stackoverflow.com/q/13243975/1497596): *"This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread."* – DavidRR May 31 '16 at 18:02