简体   繁体   English

异步地向Viewport3D添加一个子级将提供“使用错误上下文的参数访问此API的信息。”

[英]Adding a child to Viewport3D asynchronously gives “This API was accessed with arguments from the wrong context.”

When I try to add 3D-content to a Viewport3D, asynchronously, this results in "This API was accessed with arguments from the wrong context." 当我尝试将3D内容异步添加到Viewport3D时,这导致“使用错误的上下文中的参数访问了此API”。 in a TargetInvocationException. 在Tar​​getInvocationException中。

The 3D-content is generated from the data of a 3D-scanning device. 从3D扫描设备的数据生成3D内容。 The communication&calculations needed for that are done in a separate thread. 为此所需的通信和计算在单独的线程中完成。 First, I tried to acces the viewport3D from that thread. 首先,我尝试从该线程访问viewport3D。 I realized this should be done by the GUI-thread, so now I use this code: 我意识到这应该由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);

It seems that the object named "model" is not in the context of the current thread. 似乎名为“模型”的对象不在当前线程的上下文中。 How can I fix this? 我怎样才能解决这个问题? Is there a way to get the model to the context of the Dispatcher? 有没有一种方法可以使模型适应分派器的环境? Or is this way of doing this just not the way to go here? 还是这种方式不是去这里的方式?

This will occur when ever you generate/modify scene objects to add to Viewport, from a different thread then the one Viewport was instantiated on. 每当您生成/修改场景对象以从实例化一个Viewport的另一个线程生成/修改场景对象以将其添加到Viewport时,就会发生这种情况。 There is a simple work around. 有一个简单的解决方法。 Encapsulate the code that updates Viewport objects into a function. 将将视口对象更新的代码封装到一个函数中。 Insert the following snippet and you are done. 插入以下代码片段,即可完成操作。

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); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM