WPF Dispatcher.BeginInvoke和UI /背景线程 [英] WPF Dispatcher.BeginInvoke and UI/Background Threads
问题描述
我认为我需要对WPF Dispatcher.Invoke 和 Dispatcher.BeginInvoke 的用法进行一些说明。
I think I need some clarifications regarding WPFs Dispatcher.Invoke and Dispatcher.BeginInvoke usage.
假设我有一些长期运行的工作代码,例如在简单的WPF应用程序中按一下按钮即可调用的代码:
Suppose I have some long running 'work' code like such that is invoked on the press of a button in a simple WPF application:
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线程上运行,对吧?
This code is locking up my user interface while the workAction is being performed. This is because Dispatcher invokes always run on the UI thread, right?
假设这样做,配置我的调度程序以执行的最佳实践是什么我是否可以在与UI分开的线程中使用workAction ??我知道可以在 workAction 中添加 BackgroundWorker 来防止UI锁定:
Assuming this, what is the best practice for configuring my dispatcher to execute the workAction in a separate thread from my UI? I know I can add a BackgroundWorker to my workAction to prevent my UI from locking as such:
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 很古怪,所以我很想知道一些替代方法。
Is there any more elegant ways of doing this besides using the BackgroundWorker? I've always heard that the BackgroundWorker is quirky, so I am curious to know of some alternatives.
推荐答案
老实说,我认为 BackgroundWorker
是最优雅的解决方案。我想不出更简单的方法。
I honestly think the BackgroundWorker
is the most elegant solution for this. I cannot think of a simpler way to do it.
这篇关于WPF Dispatcher.BeginInvoke和UI /背景线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!