I am new to wpf and multithreading. I have five UserControl, A-B-C-D-E and goes back to A
I'm trying to reload the userControl A when B is loaded.
public class Main{
public List<Page> pages;
public UserControl currentScreen;
}
public class Page
{
public UserControl userControl;
public String xamlUrl;
public void Invalidate()
{
try{
var th = new Thread(() =>
{
ParseUserControl(xamlUrl);
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
}
}
void ParseUserControl(String xamlUrl)
{
Console.WriteLine("ParseUserControl" + Thread.CurrentThread.ManagedThreadId);
string strXaml = System.IO.File.ReadAllText(xamlUrl);
UserControl uc = (UserControl)System.Windows.Markup.XamlReader.Parse(strXaml);
UserControlParsedEventArgs args = new UserControlParsedEventArgs(uc);
Application.Current.Dispatcher.Invoke(() => UserControlParsed(args));
}
void UserControlParsed(UserControlParsedEventArgs e)
{
Console.WriteLine("UserControlParsed " + Thread.CurrentThread.ManagedThreadId);
userControl= e.userControl;
Main.getInstance().currentScreen = userControl; //this line here throws error
}
}
The main idea is to have a thread parse the user control and after the user control is loaded, we send it back to the main screen to display.
However, I get this error : "The calling thread cannot access this object because a different thread owns it."
I'm thinking it's because the UserControl is created in different thread, but I already did UserControl uc = e.userControl.
I've checked the thread ID:
main is running on id 8 <----------------------
ParseUserControl is running on id 9 |---always same
UserControlParsed is running on id 8 <---------
so the UserControl in UserControlParsed belongs to thread 8 and supposedly can be used in main? I'm confused.