Why does “await LoadAsync()” freeze the UI while “await Task.Run(() => Load())” does not?

折月煮酒 提交于 2019-12-18 07:12:26

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/27051169/why-does-await-loadasync-freeze-the-ui-while-await-task-run-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!