1

我一直在尝试在一个窗口的背景中加载另一个窗口;在我的情况下,父窗口充当启动屏幕。

InitWindow I = null;
    public InitWindow()
    {
        InitializeComponent();
        I = this;

        Thread T = new Thread(() =>
        {
            MainWindow M = new MainWindow();
            M.Show();
            M.ContentRendered += M_ContentRendered;
            System.Windows.Threading.Dispatcher.Run();
            M.Closed += (s, e) => M.Dispatcher.InvokeShutdown();

        }) { IsBackground = true, Priority = ThreadPriority.Lowest };

        T.SetApartmentState(ApartmentState.STA);
        T.Start();
    }

    void M_ContentRendered(object sender, EventArgs e)
    {
        I.Close();
    }

其他一切正常,但它会在以下位置引发 Invalid Operation Exception:

I.Close();

调用线程无法访问此对象,因为不同的线程拥有它。

1)如何切换/同步线程?

2)有更好的解决方法吗?

4

1 回答 1

2

将代码更改为:

    InitWindow I = null;
    Thread C = null;  

    public InitWindow()
    {
        InitializeComponent();
        I = this;
        C = Thread.CurrentThread;  

        Thread T = new Thread(() =>
        {
            MainWindow M = new MainWindow();
            M.Show();
            M.ContentRendered += M_ContentRendered;
            System.Windows.Threading.Dispatcher.Run();
            M.Closed += (s, e) => M.Dispatcher.InvokeShutdown();

        }) { IsBackground = true, Priority = ThreadPriority.Lowest };

        T.SetApartmentState(ApartmentState.STA);
        T.Start();
    }

    void M_ContentRendered(object sender, EventArgs e)
    {
        // Making the parent thread background
        C.IsBackground = true; 
        // foreground the current thread
        Thread.CurrentThread.IsBackground = false;
        // Abort the parent thread
        C.Abort();
    }

到目前为止工作正常,但我认为这不是一个可靠的解决方案。

于 2013-07-12T12:10:23.943 回答