I am trying to make a simple game in C#/XAML. I have a worker thread which calculates the new positions of the game elements each tick and then updates the UI with new positions. Or at least it should be.
Instead, the output says:
A first chance exception of type 'System.Exception' occurred in Game.exe
An exception of type 'System.Exception' occurred in Game.exe but was not handled in user code
The thread '<No Name>' (0x1218) has exited with code 0 (0x0).
I’ve sifted through this with break points, and the code breaks in this area.
//Stop previous animation in case it is ongoing
GameStoryboard.Stop();
//Remove all previous timelines from the storyboard
foreach (Timeline timeline in GameStoryboard.Children)
{
GameStoryboard.Children.Remove(timeline);
}
The first line of code there crashes it, but I can comment out the GameStoryboard.Stop() line (it’s only relevant in case the game’s tick time is automatically lowered between loops), and then it just crashes on the foreach loop instead. If I comment out the foreach loop, it crashes on the next time I reference GameStoryboard.
The declaration for GameStoryboard looks like this:
<Canvas Name="GameCanvas" Height="900" Width="1440" Background="Blue">
<Canvas.Resources>
<Storyboard x:Name="GameStoryboard"/>
</Canvas.Resources>
</Canvas>
The only theory I can think of is, do XAML objects not let you reference them from a different thread than the one which initialized it? If so, what’s the best way to do what I’m trying to? And if not, anyone have any idea what could be causing this?
As Alex said, you can only access DependencyObjects from the thread that created them.
You can use the Dispatcher to execute your code on the UI thread to access your ‘StoryBoard’. For example if you were using a BackgroundWorker in your code-behind: