【问题标题】:Multi-thread UI, unable to BeginInvoke多线程 UI,无法 BeginInvoke
【发布时间】:2013-08-29 22:36:43
【问题描述】:

我需要在与主 UI 线程不同的线程上启动一个窗口。这不理想,我知道这不正常。

新窗口启动如下:

private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            var thread = new Thread(() =>
                {
                    var w = new ScrollingBanner(300,70,0,0);
                    w.Show();
                    w.Name = "BannerThread";

                    w.Closed += (sender2, e2) => w.Dispatcher.InvokeShutdown();

                    Dispatcher.Run();
                });               
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();

        }

这会启动窗口并执行我需要的操作。

这个(线程化)UI的Window上的控件调用了一个我在窗口后面的代码中监听的事件,如下:

 private void ContentTicker_OnScrollComplete(object sender, EventArgs e)
    {
        Debug.WriteLine("Scroller Ended");

        try
        {
            if (CheckAccess())
            {
                sliderText.Text = "Updated Text";
            }
            else
            {
                Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                       new Action(() => sliderText.Text = "Updated Text"));
            }
        }
        catch (Exception ex)
        {
            //breakpoint
        }        
    }

ContentTicker_OnScrollComplete 从控件运行的后台线程调用。

我得到一个异常,不同的线程拥有该控件;但据我所知,我正在调用 Dispatcher 以在正确的线程上执行操作。 (如果我在主 UI 线程上执行所有这些操作,它会起作用)

如何在正确的线程上更新“sliderText”?

谢谢

【问题讨论】:

    标签: c# wpf multithreading


    【解决方案1】:

    替换这个:

    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                       new Action(() => sliderText.Text = "Updated Text"))
    

    为此:

    Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                       new Action(() => sliderText.Text = "Updated Text"))
    

    因为Application.Current.Dispatcher 将返回“主要”调度程序,而不是“次要”调度程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      相关资源
      最近更新 更多