为什么在不同的线程中创建窗口时,有时会出现"无效的窗口句柄"异常

Sam*_*ath 2 c# wpf multithreading

在按照以下代码Invalid window handle创建时,我会遇到" "异常Window.这是在一个单独的线程上调用的.它不是每次都抛出,而是随机发生的.此外,我无法查看异常的堆栈跟踪,它说" {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}"

private void ShowDialog()
{
    Thread thread = new Thread(() =>
        {
            waitContainer = MakeSimpleWindow();
            this.waitContainer.Closed += new EventHandler(waitingWindow_Closed);

            waitContainer.ShowDialog();

            System.Windows.Threading.Dispatcher.Run();
        });
        thread.SetApartmentState(ApartmentState.STA);
        thread.IsBackground = true;
        thread.Start();
}

public Window MakeSimpleWindow()
    {
        Window w = new Window(); // Exception occurs from here
        w.Title = Attributes[MessageBoxAttribute.message];            
        return w;
    }
Run Code Online (Sandbox Code Playgroud)

Hen*_*man 5

2行:

waitContainer.ShowDialog();\    
System.Windows.Threading.Dispatcher.Run();
Run Code Online (Sandbox Code Playgroud)

至少有一个竞争条件.当ShowDialog开始执行时,Thread尚未运行Dispatcher.

但答案不是如何解决这个问题.虽然你可以执行更多的1个调度程序,但它很少是个好主意.寻找一个运行1个GUI线程(主线程)的解决方案,并解决Invoke和事件的其他问题.