-1

How to create UserControl (any graphical component) in a separate thread and then thread it to the main thread. True the ruler works and it goes back to the main thread. But it seems that it is not possible to produce UserControl in a separate thread from the main thread

   public partial class LifePattern : UserControl
    {
        Thread t;
        public LifePattern()
        {
            InitializeComponent();
            t = new Thread(CreateUiElemet);
            t.IsBackground = true;
            t.SetApartmentState(ApartmentState.STA);
            t.Name = "Thread Create Control";
            t.Start();
        }

        private void CreateUiElemet(object obj)
        {
            // Create in this Thread the Control
            UserControl userControl = new UserControl();

            // Back to the thread Main
            Application.Current.Dispatcher.Invoke(() =>
            {
                btn_Play.Content = userControl;
                //System.InvalidOperationException:
                //'The calling thread cannot access this object because a different thread owns it.'
            });
        }
    }
  • this.Dispatcher.Invoke(() => { ...// your code here. }); This still does not solve the problem because then the UserControl created in the second thread does not successfully move to the main thread – יעקב פרידמן May 09 '21 at 20:35

1 Answers1

0
new CreatesVCControl();

Don't create this UI control in a foreign thread. Create it on the UI thread. Your best bet is to optimize how CreatesVCControl works.

Lemon Sky
  • 677
  • 4
  • 10
  • I intentionally create CreatesVCControl in a separate thread. Because the process takes a very long time .. – יעקב פרידמן May 09 '21 at 20:32
  • The control is bound to the thread that you created it on. – Lemon Sky May 09 '21 at 20:43
  • yes, the the user control is created in the second thread – יעקב פרידמן May 09 '21 at 20:59
  • UserControls are not thread-safe, you can touch them from exactly one thread only. You can't create them on one thread, and use them in another. I know what you're trying to achieve, but it is not possible in pure WinForms or WPF. You can mix and match hwnd's belonging to different processes or threads using low-level Win32 APIs only. – Lemon Sky May 09 '21 at 21:12
  • That is, there is no way to create UI strings in one thread and move it to another thread? – יעקב פרידמן May 09 '21 at 21:36
  • You can prepare data whetever you like as long as the control is not aware of it. Any code that triggers the control has to be on the UI thread. – Lemon Sky May 10 '21 at 17:56