将子项异步添加到 Viewport3D 会给出“此 API 使用来自错误上下文的参数访问." [英] Adding a child to Viewport3D asynchronously gives "This API was accessed with arguments from the wrong context."

查看:22
本文介绍了将子项异步添加到 Viewport3D 会给出“此 API 使用来自错误上下文的参数访问."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将 3D 内容异步添加到 Viewport3D 时,这会导致使用来自错误上下文的参数访问此 API."在 TargetInvocationException 中.

When I try to add 3D-content to a Viewport3D, asynchronously, this results in "This API was accessed with arguments from the wrong context." in a TargetInvocationException.

3D 内容是根据 3D 扫描设备的数据生成的.为此所需的通信和计算在单独的线程中完成.首先,我尝试从该线程访问 viewport3D.我意识到这应该由 GUI 线程完成,所以现在我使用以下代码:

The 3D-content is generated from the data of a 3D-scanning device. The communication&calculations needed for that are done in a separate thread. First, I tried to acces the viewport3D from that thread. I realized this should be done by the GUI-thread, so now I use this code:

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

似乎名为model"的对象不在当前线程的上下文中.我怎样才能解决这个问题?有没有办法让模型进入 Dispatcher 的上下文?或者,这样做的方式不适合这里?

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?

推荐答案

当您从不同的线程生成/修改场景对象以添加到视口时,就会发生这种情况,然后实例化一个视口.有一个简单的解决方法.将更新 Viewport 对象的代码封装到一个函数中.插入以下代码段,您就完成了.

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

这篇关于将子项异步添加到 Viewport3D 会给出“此 API 使用来自错误上下文的参数访问."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆