WPF Dispatcher.BeginInvoke和UI /后台线程

Mat*_*ton 18 wpf user-interface multithreading dispatcher

我想我需要对WPF Dispatcher.InvokeDispatcher.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);
Run Code Online (Sandbox Code Playgroud)

此代码在执行workAction时锁定了我的用户界面.这是因为Dispatcher调用总是在UI线程上运行,对吧?

假设这样,配置我的调度程序在我的UI的单独线程中执行workAction的最佳做法是什么?我知道我可以在我的workAction中添加BackgroundWorker, 以防止我的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);
Run Code Online (Sandbox Code Playgroud)

除了使用BackgroundWorker之外,还有更优雅的方法吗?我一直听说BackgroundWorker很古怪,所以我很想知道一些替代品.

Cha*_*lie 25

老实说,我认为这BackgroundWorker是最优雅的解决方案.我想不出更简单的方法.