我想我需要一些关于 WPF Dispatcher.Invoke和Dispatcher.BeginInvoke用法的说明。
假设我有一些长时间运行的“工作”代码,例如在简单的 WPF 应用程序中按下按钮时调用:
longWorkTextBox.Text = "Ready For Work!";
Action workAction = delegate
{
Console.WriteLine("Starting Work Action");
int i = int.MaxValue;
while (i > 0)
i--;
Console.WriteLine("Ending Work Action");
longWorkTextBox.Text = "Work Complete";
};
longWorkTextBox.Dispatcher.BeginInvoke(DispatcherPriority.Background, workAction);
此代码在执行workAction时锁定了我的用户界面。这是因为 Dispatcher 调用总是在 UI 线程上运行,对吗?
假设这一点,将调度程序配置为在与我的 UI 不同的线程中执行workAction的最佳实践是什么?我知道我可以将BackgroundWorker添加到我的workAction 以防止我的 UI 被锁定:
longWorkTextBox.Text = "Ready For Work!";
Action workAction = delegate
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate
{
Console.WriteLine("Starting Slow Work");
int i = int.MaxValue;
while (i > 0)
i--;
Console.WriteLine("Ending Work Action");
};
worker.RunWorkerCompleted += delegate
{
longWorkTextBox.Text = "Work Complete";
};
worker.RunWorkerAsync();
};
longWorkTextBox.Dispatcher.BeginInvoke(DispatcherPriority.Background, workAction);
除了使用BackgroundWorker之外,还有其他更优雅的方法吗?我一直听说BackgroundWorker很古怪,所以我很想知道一些替代方案。