How do I open a window on a new thread?

后端 未结 3 808
离开以前
离开以前 2021-02-08 12:48

I have a options window and a window that displays color based on these options and Kinect data. So far everything\'s on one thread (as far as I know; I haven\'t done any thread

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-08 13:15

    You need to call Show() on the same thread that the window is created on - that's why you are getting the error. Then you also need to start a new Dispatcher instance to get the runtime to manage the window.

    private void launchViewerThread_Click(object sender, RoutedEventArgs e)
    {
        Thread viewerThread = new Thread(delegate()
        {
            viewer = new SkeletalViewer.MainWindow();
            viewer.Show();
            System.Windows.Threading.Dispatcher.Run();
        });
    
        viewerThread.SetApartmentState(ApartmentState.STA); // needs to be STA or throws exception
        viewerThread.Start();
    }
    

    See the Multiple Windows/Multiple Threads example at: http://msdn.microsoft.com/en-us/library/ms741870.aspx

提交回复
热议问题