增加一个孩子Viewport3D异步给"这API访问与参数,从错误的上下文。"
-
05-07-2019 - |
题
当我试图添加3D内容Viewport3D、异步,这种结果在"这API访问与参数,从错误的上下文"。在这样的.
3D-的内容是从数据产生的一个3D-扫描设备。的通信和计算需要完成在一个单独的螺纹。首先,我想存取权限的viewport3D从该线。我意识到这项工作应由GUI线,所以现在我使用这个代码:
ModelVisual3D model = new ModelVisual3D();
model.Content = scanline;
DispatcherOperation dispOp = this.viewport.Dispatcher.BeginInvoke(
new AddModelDelegate(StartAddModel), model);
}
private void StartAddModel(ModelVisual3D model)
{
this.viewport.Children.Add(model);
//model is not in the context of this current thread.
//Throws exception: "This API was accessed with arguments from the wrong context."
}
private delegate void AddModelDelegate(ModelVisual3D model);
似乎对象的名为"模型"是不是在上下文中的前线。我如何能解决这个问题?有没有办法获得模型方面的调度员?或是这种方式这样做只是不要去这里吗?
解决方案
这将会永远当你的生成/修改现场的对象添加到视,从一个不同的线,然后一个视是实例。有一个简单的解决。封装的代码的更新视的对象,成为一个功能。插入以下段和你做。
private delegate void MyFunctionDelegate();
void MyFunction()
{
if(!Application.Current.Dispatcher.CheckAccess())
{
Application.Current.Dispatcher.Invoke(new MyFunctionDelegate(MyFunction));
return; // Important to leave the culprit thread
}
.
.
.
this.Viewport3D.Children.Remove(model);
MyModifyModel(model);
this.Viewport3D.Children.Add(model);
}
不隶属于 StackOverflow