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?