-2

I want to create custom usercontrol dynamically in different thread. My code is

var thread = new Thread(() =>
{
    var uc = new UserControl05();

    UserControl item = uc;

    Parallel.ForEach(_allTabs, currentTab =>
    {
        if (currentTab.DocumentWindow.CheckAccess())
        {
            if (currentTab.DocumentWindow.IsSelected)
            {
               //some code
            }
        }
        else
        {
            currentTab.DocumentWindow.Dispatcher.BeginInvoke(new Action(() =>
            {                            
                if (!currentTab.DocumentWindow.IsSelected) return;
                if (currentTab.AnimatedCanvas.CheckAccess())
                {
                    currentTab.AnimatedCanvas.Children.Add(item); //here I get error
                }
                else
                {     
                    currentTab.AnimatedCanvas.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        currentTab.AnimatedCanvas.Children.Add(item);
                    }));
                }
            }));
        }
     });

});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true; 
thread.Name = "Create Control";
thread.Start();

I get error the calling thread cannot access this object because a different thread owns it. I searched for the solution and tryed to use dispatcher there, but it doesn't help and throws the same error. I understand it's happening because I've created usercontrol on background thread but how to fix it I have no idea.

Can anybody suggest something?

Sasha
  • 833
  • 1
  • 20
  • 40
  • 1
    You cannot create the control on another thread... – H.B. Jul 03 '13 at 13:04
  • Is there any possibility to do that? Or I must to do that only on main thread? – Sasha Jul 03 '13 at 13:06
  • Use the main (i.e. UI) thread, that is where you will use the control, you can still manipulate it on other threads via the `Dispatcher`. – H.B. Jul 03 '13 at 13:09

1 Answers1

0

WPF Apps start with two threads, a UI thread and a rendering thread. You must create your usercontrol on the UI thread.

user2509738
  • 219
  • 1
  • 6