【问题标题】:Threading problem in WPFWPF中的线程问题
【发布时间】:2009-04-08 14:22:08
【问题描述】:

我得到了这个异常

System.InvalidOperationException 是 用户代码未处理 Message="The 调用线程无法访问此 对象,因为不同的线程拥有 它。”

每当我运行以下代码时

public partial class MainScreen : Window
{
        Timer trm;

        public MainScreen()
        {
            InitializeComponent();

            trm = new Timer(1000);
            trm.AutoReset = true;
            trm.Start();
            trm.Elapsed += new ElapsedEventHandler(trm_Elapsed);
        }

        void trm_Elapsed(object sender, ElapsedEventArgs e)
        {
            lblTime.Content = System.DateTime.Now;
        }
}

各位有什么解决办法...我很想摆脱它:(

【问题讨论】:

    标签: wpf multithreading


    【解决方案1】:

    改用 DispatcherTimer:

    public partial class MainScreen : Window{
    DispatcherTimer tmr;    
    public MainScreen() {
    InitializeComponent();
    tmr = new DispatcherTimer();
    tmr.Tick += new EventHandler(tmr_Tick);
    tmr.Start();    
    }
    void tmr_Tick(object sender, EventArgs e) {
        lblTime.Content = System.DateTime.Now;
    }
    }
    

    【讨论】:

      【解决方案2】:

      每当您修改 Windows 控件时,都必须在 UI 线程(创建控件的线程)上进行。

      详情请见this question

      【讨论】:

        【解决方案3】:

        简而言之,您应该使用 Dispatcher.Invoke 方法来更新 UI 元素。

        【讨论】:

          猜你喜欢
          • 2013-01-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多