子线程中的进度条更新不更新,主线程中完成的工作

Progress bar update in child thread not updating, Work done in main thread

我有一个应用程序,它有一个 C# 前端(GUI 客户端)和一个 C++ 后端(业务逻辑)。后端负责请求进度条功能,并通过发出事件来实现这一点,前端有观察员代表来响应和采取行动。所以事件在主线程中被调度和响应。

我想生成第二个线程来显示和更新进度条,因为主线程被后端占用。虽然我可以按预期显示进度条 window,并在完成后正确隐藏,但它不会响应 updates/increments。

ProgressBarWindow 持有进度条控件 (pBar)。 ProgressBarWindowprogressBarThread 所有。

public static EventObserver.ProgressBeginEvent pbe = null;
public static EventObserver.ProgressFinishEvent pfe = null;
public static EventObserver.ProgressIncrementEvent pie = null;
public static Thread progressBarThread = null;

static private void InitialiseProgressBarManager()
{

    // Setup the progress bar callbacks...
    pbe = new EventObserver.ProgressBeginEvent(delegate
        (int currentIncrements, int totalIncrements, string message)
    {
        // Create the thread and progress bar window...
        progressBarThread = new Thread(() =>
        {
            ProgressBarWindow sw = new ProgressBarWindow();
            sw.pBar.IsIndeterminate = false;
            sw.pBar.Minimum = currentIncrements.Value;
            sw.pBar.Maximum = totalIncrements.Value;
            sw.pBar.Value = 0;
            sw.Show();

            pie = new EventObserver.ProgressIncrementEvent(delegate ()
            {
                sw.pBar.Value++;        // The calling thread cannot access this object... see below 
            });

            pfe = new EventObserver.ProgressFinishEvent(delegate ()
            {
                progressBarThread.Abort();
                progressBarThread = null;
            });
        });

        progressBarThread.SetApartmentState(ApartmentState.STA);
        progressBarThread.IsBackground = true;
        progressBarThread.Start();
    });
}

window 按预期显示,并且 ProgressIncrementEvent 正确引发(它由线程拥有),但是当它尝试访问该值时出现异常。

The calling thread cannot access this object because a different thread owns it.

我需要互斥体或其他锁吗?我希望观察者委托的范围允许委​​托对本地线程 ProgressBarWindow 进行可变访问,即使它是从主线程调用的?

我不是出色的 C# 开发人员,更不是 C# 线程开发人员,所以我对我应该在这里做什么或者即使我可以实现这种行为有点困惑。任何帮助或指导让这项工作将不胜感激。

P.S 我正在使用 WPF,ProgressBarWindow 在 XAML 中定义。

尝试使用 window 的调度程序访问控件:

sw.Dispatcher.BeginInvoke(new Action(() => sw.pBar.Value++));