When correctly use Task.Run and when just async-await

前端 未结 2 1096
清酒与你
清酒与你 2020-11-22 09:55

I would like to ask you on your opinion about the correct architecture when to use Task.Run. I am experiencing laggy UI in our WPF .NET 4.5 application (with Ca

2条回答
  •  礼貌的吻别
    2020-11-22 10:38

    One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get

    public class PageViewModel : IHandle
    {
       ...
    
       public async void Handle(SomeMessage message)
       {
          ShowLoadingAnimation();
    
          // makes UI very laggy, but still not dead
          await this.contentLoader.LoadContentAsync(); 
    
          HideLoadingAnimation();   
       }
    }
    
    public class ContentLoader 
    {
        public async Task LoadContentAsync()
        {
            var tasks = new List();
            tasks.Add(DoCpuBoundWorkAsync());
            tasks.Add(DoIoBoundWorkAsync());
            tasks.Add(DoCpuBoundWorkAsync());
            tasks.Add(DoSomeOtherWorkAsync());
    
            await Task.WhenAll(tasks).ConfigureAwait(false);
        }
    }
    

    Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.

提交回复
热议问题