我想问一下您对使用Task.Run时的正确架构的看法。我正在经历滞后的用户界面在我们的WPF .NET 4.5 应用程序(与Caliburn Micro框架)。
基本上我在做(非常简化的代码片段):
public class PageViewModel : IHandle<SomeMessage>
{
...
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()
{
await DoCpuBoundWorkAsync();
await DoIoBoundWorkAsync();
await DoCpuBoundWorkAsync();
// I am not really sure what all I can consider as CPU bound as slowing down the UI
await DoSomeOtherWorkAsync();
}
}
从我阅读/看到的文章/视频中,我知道await async不一定在后台线程上运行,要在后台开始工作,你需要用await Task来包装它。运行(async() =>…). 使用async await并不会阻塞UI,但它仍然运行在UI线程上,因此它会使UI线程延迟。
哪里是放置Task.Run的最佳位置?
我应该
包装外部调用,因为这减少了。net的线程工作 ,或者我应该只包装cpu绑定的方法内部运行的任务。运行,因为这使它可用于其他地方?我不确定在内核深处开始后台线程的工作是否是一个好主意。
Ad(1),第一个解为:
public async void Handle(SomeMessage message)
{
ShowLoadingAnimation();
await Task.Run(async () => await this.contentLoader.LoadContentAsync());
HideLoadingAnimation();
}
// Other methods do not use Task.Run as everything regardless
// if I/O or CPU bound would now run in the background.
Ad(2),第二个解为:
public async Task DoCpuBoundWorkAsync()
{
await Task.Run(() => {
// Do lot of work here
});
}
public async Task DoSomeOtherWorkAsync(
{
// I am not sure how to handle this methods -
// probably need to test one by one, if it is slowing down UI
}