如何在GUI线程中执行代码? [英] How to execute code in the GUI Thread?
问题描述
我有一个FileSystemWatcher的上Changed事件作出反应。
I have a FileSystemWatcher that react on the Changed event.
我想打开该文件,读取其内容的文本框显示它和隐藏有弹出1秒之后被创建。该代码几乎工作,但隐藏弹出当事情失败
I want to open the file, read its content display it in a textbox and hide the popup that has been created after 1 sec. The code almost work but something fail when hiding the popup.
下面是代码片段:
txtLog.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate() {
this.txtLog.Text = dataToDisplay;
extendedNotifyIcon_OnShowWindow();
Thread threadToClosePopup = new Thread(new ThreadStart((Action)delegate() {
Thread.Sleep(1000);
extendedNotifyIcon_OnHideWindow();
}));
threadToClosePopup.Start();
});
正如你所看到的,我使用Invoke设置文本,因为该事件是在不同的线程(FileSystemWatcher的)。但隐藏extendedNotifyIcon_OnHideWindow()不是在GUI的线程执行的窗口。我怎样才能在GUI线程中执行呢?
As you can see, I use the Invoke to set the text because the event is in a different thread (FileSystemWatcher). But to hide the windows the extendedNotifyIcon_OnHideWindow() is not executed in the thread of the GUI. How can I execute it in the GUI thread?
推荐答案
要执行 extendedNotifyIcon_OnHideWindow
GUI线程的方法使用调度
像你一样表现出来。
To execute the extendedNotifyIcon_OnHideWindow
method on the GUI thread use the Dispatcher
as you did to show it.
Thread threadToClosePopup = new Thread(new ThreadStart((Action)delegate() {
Thread.Sleep(1000);
txtLog.Dispatcher.Invoke(
DispatcherPriority.Normal,
(Action)() => extendedNotifyIcon_OnHideWindow());
}));
这篇关于如何在GUI线程中执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!