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

前端 未结 1 1657
被撕碎了的回忆
被撕碎了的回忆 2020-12-19 22:37

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

相关标签:
1条回答
  • 2020-12-19 22:49

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

    0 讨论(0)
提交回复
热议问题