我正在尝试在后台执行操作,而不卡住UI。
当然,我可以为此使用BackgroundWorker。
但是,我只想使用Task API来做到这一点。
我试过了:
async void OnTestLoaded(object sender, RoutedEventArgs e)
{
await LongOperation();
}
// It freezes the UI
和
async void OnTestLoaded(object sender, RoutedEventArgs e)
{
var task = Task.Run(()=> LongOperation());
task.Wait();
}
// It freezes the UI
那我应该回到BackgroundWorker吗?还是仅使用任务有解决方案?
最佳答案
你很亲密。
async void OnTestLoaded(object sender, RoutedEventArgs e)
{
await Task.Run(() => LongOperation());
}
async
does not execute a method on a thread pool thread。Task.Run
在线程池线程上执行操作,并返回代表该操作的Task
。如果在
Task.Wait
方法中使用async
,则为doing it wrong。您应该在await
方法中使用async
任务,切勿阻塞它们。
关于wpf - 运行长任务而不卡住UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10065000/