【发布时间】:2016-08-11 03:04:28
【问题描述】:
我想我需要对 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 很古怪,所以我很想知道一些替代方案。
【问题讨论】:
标签: wpf multithreading user-interface dispatcher