Question

I have a Visual3D object loaded from a file and displaying on screen. That works fine. I am trying to rotate it from data received in a SerialDataReceivedEventHandler - which also works fine.

When I try to rotate the model, it throws an InvalidOperationException because the thread doesn't own the object. Here's what I have:

QuaternionRotation3D rotation = new QuaternionRotation3D(q);
model.Dispatcher.BeginInvoke(new Action(() => 
           model.Transform = new RotateTransform3D(rotation)));

I know I need to use the dispatcher, but I can't figure out how.

Was it helpful?

Solution

I assume all the code you posted is called inside another thread, so you wont be able to create the QuaternionRotation3D on that thread, There are a few ways to solve this but without seeing the rest of your code its hard to guess but one of these options should work.

Application.Current.Dispatcher.BeginInvoke(new Action(() => 
{
    QuaternionRotation3D rotation = new QuaternionRotation3D(q);
    model.Transform = new RotateTransform3D(rotation);
}));

Or if its just on the MainWindow

Dispatcher.BeginInvoke(new Action(() => 
{
    QuaternionRotation3D rotation = new QuaternionRotation3D(q);
    model.Transform = new RotateTransform3D(rotation);
}));

Or if model is threadsafe (no Observables/dependancy properties)

model.Dispatcher.BeginInvoke(new Action(() => 
{
    QuaternionRotation3D rotation = new QuaternionRotation3D(q);
    model.Transform = new RotateTransform3D(rotation);
}));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top