I have fairly straightforward code that I want to run in order to edit the UI. I know that the UI will freeze if I run it in the Main Thread so I have been working at running it in a separate Thread, but this is not working. Here is what I want to happen: The user populates two lists using the UI. One list keeps track of what is on the screen and the other keeps track of what will need to go on the screen later. When the user clicks a certain button it clears the first list and the UI. I then display each item on the UI again using the second list with a certain length of time in between the return of each object. Here it is in a simplified form:
myList = [/*items to be displayed*/];
myMessages = [/*items currently displayed*/]
private void ButtonAnimationRun(object sender, RoutedEventArgs e)
{
Thread thread = new Thread(() =>
{
Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
public void Run()
{
foreach (Message message in myList)
{
Thread.Sleep(message.Time * 1000);
CreateText(message.Text);
}
}
public void CreateText(string text)
{
Dispatcher.Invoke(() => myGrid.Children.Add(myMessages[myMessages.Count - 1]));
// text is added to the child of myGrid here
Dispatcher.Invoke(() => myScrollBar.ScrollToBottom());
}
That is not all my code, but it is the code that is related to my problem. If I use await or tasks I get an Apartment State error. With the code above I get this error: 'The calling thread cannot access this object because a different thread owns it.' on the line of the first Invoke, with or without the Invoke I still get it. The second Invoke works just fine when I comment out the previous one, but then, or course, I don't get anything shown on the UI because that is the code that adds the UI element to the UI. I have searched stackoverflow and all the answers I find cause others to crop up or inhibit the functionality of my app. If you need more information I can provide it.