创建另一个线程以获取当前窗口(System.Windows.Application.Current.MainWindow)

时间:2011-08-30 19:55:24

标签: c# wpf

我需要当前窗口来显示自定义MessageBox。我这样做:

Window owner = System.Windows.Application.Current.MainWindow;

有时它有效。如果它不起作用,我会收到此错误:

System.InvalidOperationException: {"The calling thread cannot access this object because a different thread owns it."}
InnerException: null
Message: The calling thread cannot access this object because a different thread owns it.

解决方案是将这个调用踢到一个单独的线程而不是主线程吗?如果是这样,我该怎么做?感谢。

2 个答案:

答案 0 :(得分:10)

您需要使用Dispatcher和Invoke / BeginInvoke将回调编组回UI线程:

System.Windows.Application.Current.Dispatcher.Invoke((Action)() =>
{
       Window owner = System.Windows.Application.Current.MainWindow;

       // Use owner here - it must be used on the UI thread as well..
       ShowMyWindow(owner);
});

答案 1 :(得分:0)

里德·科普西答案的替代方法:

System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate
{
       Window owner = System.Windows.Application.Current.MainWindow;

       // Use owner here - it must be used on the UI thread as well..
       ShowMyWindow(owner);
});