Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

.net - Why does "await LoadAsync()" freeze the UI while "await Task.Run(() => Load())" does not?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...