How do I open a window on a new thread?

后端 未结 3 813
离开以前
离开以前 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:27

    I am not sure if this will solve your problem but can you try creating a thread proc (to open a viewer window) which is executed on a different thread and then have a dispatcher.beginInvoke to update the main window ,

    Here is some code-

        in the constructor register this
        public MainWindow()
        { 
           UpdateColorDelegate += UpdateColorMethod;
        } 
    
        // delegate and event to update color on mainwindow 
        public delegate void UpdateColorDelegate(string colorname);
        public event UpdateColorDelegate updateMainWindow;
    
        // launches a thread to show viewer
        private void launchViewerThread_Click(object sender, RoutedEventArgs e)
        {
            Thread t = new Thread(this.ThreadProc);
            t.Start();
        }
    
        // thread proc
        public void ThreadProc()
        {
           // code for viewer window
           ...
           // if you want to access any main window elements then just call DispatchToMainThread method
           DispatchToUiThread(color);   
        } 
    
        // 
        private void DispatchToUiThread(string color)
        {
          if (updateMainWindow != null)
          {
            object[] param = new object[1] { color};
            Dispatcher.BeginInvoke(updateMainWindow, param);
          }
        }
    
        // update the mainwindow control's from this method
        private void UpdateColorMethod(string colorName)
        {
           // change control or do whatever with main window controls
        } 
    

    With this you can update the main window controls without freezing it, Let me know if you have any questions

提交回复
热议问题