从不同的线程火灾事件 [英] Fire events from different thread

查看:141
本文介绍了从不同的线程火灾事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的主窗口(线程A 的),我开始一个新的线程(线程B 的),做一些工作,同时在用户等待的时间。

In my main window (Thread A), I start a new thread (Thread B) which does some work while the user waits.

主题b类火灾的事件,如果有错误或额外的信息需要从用户,线程A会听这些事件。

Thread B fires events if there is an error or extra information is required from the user, Thread A will listen to these events.

在线程A的事件监听器我需要显示对话消息给用户,我有一个自定义的对话窗口,并显示使用 dialogWindow.showDialog()。这工作得很好,但是会导致一个错误,当我尝试设置对话框的所有者,我这样做 dialogWindow.Owner = Window.GetWindow(本)

In Thread A's event listener I need to show dialog messages to the user, I have a custom dialog window and show it using dialogWindow.showDialog(). This works fine, but causes an error when I try and set the owner of the dialog, I do this dialogWindow.Owner = Window.GetWindow(this).

这是我得到的错误是:调用线程不能因为不同的线程拥有它访问该对象

The error that I get is: The calling thread cannot access this object because a different thread owns it.

什么是监听的是从不同的线程触发的事件的正确方法是什么?

推荐答案

引发一个事件从后台线程UI线程正确的方法是,该事件应该在该调度提高,
这里的关键是前手获得UIthread的调度员。

The correct way to raise an event to the UI thread from the background thread is that, the event should be raised on that Dispatcher, Key here is get the dispatcher of UIthread before hand.

UIDisaptcher.BeginInvoke((的ThreadStart)(()=> RaiseEventToUIThread()));

UIDisaptcher.BeginInvoke((ThreadStart)(() => RaiseEventToUIThread()));

在UI线程监听引发的事件也可以设置Owner属性(如窗口是由UI线程创建的)。

when the UI thread listens to the raised event it can set the Owner property(as the window was created by the UI thread).

这篇关于从不同的线程火灾事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆