在后台加载另一个窗口;渲染时,关闭父窗口

时间:2013-07-12 11:04:11

标签: c# wpf multithreading

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

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();
    }

其他一切正常,但它会在以下位置抛出无效操作异常:

I.Close();
  

调用线程无法访问此对象,因为其他线程拥有它。

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

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

1 个答案:

答案 0 :(得分: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();
    }

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