in C# WPF I have a game in which I load up the game with a thread and at the END it starts the gameloop thread. All good and well.
BUT: When the gameloop thread dynamically makes Projectile (Projectile extends Image) objects things go south. First i get: Thread must be STA because many UIComponents require this. so i set the appartmentstate. then, when i pass the object to the view and try to add it to the children off the canvas by this method:
public void addBaseElement(Image projectile)
{
this.Dispatcher.Invoke((Action)(() =>
{
myCanvas.Children.Add(projectile);
}));
}
I get this error: "The calling thread cannot access this object because a different thread owns it."
On every similar question on this site the answer to this error is: just add:
this.Dispatcher.Invoke((Action)(() =>
{
//Your code here
}));
and it will be fine, and that helps sometimes. but in this case, it doesn't solve it. Any suggestions?
EDIT: Marked duplicate with question that has the following solution:
Make the dynamically created objects in the view Thread I am sorry, but this is not a sufficient solution to this problem, if I do this, the whole architecture of my project will have to change. The dynamically created objects must be created within the gameloop thread. This according to me is the only way to do it clean and with a nice architecture.