BeginInvoke
在主线程上执行代码,而此线程也卡在模态窗口上。
FolderBrowserDialog
窗口FileSystemWatcher
类FolderBrowserDialog
”窗口(此窗口为模态)FolderBrowserDialog
“窗口仍处于打开状态(模态)时,用户使用外部编辑器更改监视文件[例如,记事本] System.Windows.Application.Current.Dispatcher.BeginInvoke (new Action(() => showMsg()));
以在仍然停留在模态对话框上的主线程上调用showMsg。 showMsg在主线程上被调用,虽然它仍然卡在FolderBrowserDialog
上,它仍然是开放的和模态的。
为什么showMsg立即被调用而不是FolderBrowserDialog
关闭后(用户选择文件夹后)?我希望在模式对话框关闭时调用showMsg。
任何想法都会受到赞赏,非常感谢!!
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
int threadIDMain = System.Threading.Thread.CurrentThread.ManagedThreadId;
CreateFileWatcher(@"C:\temp", @"myFile.txt"); // directory path + file name
}
private FileSystemWatcher Watcher;
public void CreateFileWatcher(string directoryPath, string fileName)
{
Watcher = new FileSystemWatcher();
Watcher.Path = directoryPath;
Watcher.NotifyFilter = NotifyFilters.LastWrite;
Watcher.Filter = fileName;
Watcher.Changed += new FileSystemEventHandler(OnChanged);
Watcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e) // called when the watched file is changed , this is called on a different thread
{
int threadIDChanged = System.Threading.Thread.CurrentThread.ManagedThreadId;
System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() => showMsg())); // calling "showMsg" on main thread
}
private void showMsg()
{
int threadIDshowMsg = System.Threading.Thread.CurrentThread.ManagedThreadId;
MessageBox.Show("showMsg: Here I am in thread ID: " + threadIDshowMsg); // same thread as main thread
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
using (System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog())
{
int threadIDClick = System.Threading.Thread.CurrentThread.ManagedThreadId;
dlg.ShowNewFolderButton = true;
dlg.Description = "Opened from thread Id " + threadIDClick;
System.Windows.Forms.DialogResult resultFileDialog = dlg.ShowDialog();
if (resultFileDialog == System.Windows.Forms.DialogResult.OK)
{
//handle this.
}
}
}
}
<Grid>
<Button Content="click to open file browser dialog" Height="50" Click="Button_Click_1"/>
</Grid>