I am trying to create a wpf app that shows an animated 3D model. I have working code to create the model in BuildWave (I know this works as I have used it before). However, when I moved the code to a background worker in the class of the wpf window, I get the error "The calling thread cannot access this object because a different thread owns it."
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = BuildWave();
}
private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
GeometryModel3D model = (GeometryModel3D)e.Result;
mGeometry = model.Clone(); //mGeometry is a private member of the window
if (group.Children.Contains(mGeometry)) //error is on this line
{
group.Children.Remove(mGeometry); //group is a Model3DGroup added in xaml
}
group.Children.Add(mGeometry);
System.Diagnostics.Debug.WriteLine("Added geometry to group");
}
I have searched for solutions to this and found a post that covers a problem with the same error (The calling thread cannot access this object because a different thread owns it), which suggests using Dispatcher.Invoke(). However, when I try that:
private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
GeometryModel3D model = (GeometryModel3D)e.Result;
mGeometry = model.Clone();
group.Dispatcher.Invoke(() =>
{
if (group.Children.Contains(mGeometry))
{
group.Children.Remove(mGeometry);
}
group.Children.Add(mGeometry); //error is now thrown on this line
});
System.Diagnostics.Debug.WriteLine("Added geometry to group");
}
This throws the error "Cannot use a DependencyObject that belongs to a different thread than its parent Freezable.", and again there is a post covering a similar problem (Cannot use a DependencyObject that belongs to a different thread than its parent Freezable) which suggests freezing the model which I have done in BuildWave:
GeometryModel3D model = new GeometryModel3D(WaveMesh, new DiffuseMaterial(Brushes.YellowGreen));
model.Transform = new Transform3DGroup();
model.Freeze();
return model;
What should I do to fix this?
thank you in advance.