为什么"等待LoadAsync()"冻结UI,而"等待Task.Run(()=>负载())"才不是? [英] Why does "await LoadAsync()" freeze the UI while "await Task.Run(() => Load())" does not?

查看:210
本文介绍了为什么"等待LoadAsync()"冻结UI,而"等待Task.Run(()=>负载())"才不是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面演练如何的EntityFramework结合WPF。我决定玩的异步/等待,而我在这,因为我从来没有真正收到使用它的机会(我们刚刚从VS2010 / .NET 4.0迁移到VS2013 / .NET 4.5)。获取保存按钮的处理程序是异步是一件轻而易举的,而UI仍然响应(我可以拖动窗口周围),而SaveChangesAsync()是期待已久。在窗口加载处理,但是,我遇到了一个小的障碍。

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

当我使用加载_context.Categories的第一种方式,用户界面​​保持响应,但是当我替补与下面的注释掉的行,在UI冻结的一瞬间,而实体的负载。有没有人对为什么以前的作品,而后者则没有解释?这不是一个大问题,它只是缠着我,第二行没有的时候,据我研究过有关异步至少工作/待机到目前为止,它应该。

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.

推荐答案

即使一个方法结束*异步并不意味着它是完全异步或异步的。 ..

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

例如:

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

用法(看起来像一个异步调用):

Usage (looks like an async call):

await FooAsync();

样品的方法是,即使它返回一个任务完全同步的。你需要检查 LoadAsync 的实施,并确保没有阻止。

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.

在使用 Task.Run 一切都在拉姆达执行异步...(或至少不阻塞调用线程)。

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

这篇关于为什么"等待LoadAsync()"冻结UI,而"等待Task.Run(()=>负载())"才不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆