子をViewport3Dに非同期的に追加すると、“このAPIは間違ったコンテキストの引数でアクセスされました。”
-
05-07-2019 - |
質問
非同期で3DコンテンツをViewport3Dに追加しようとすると、「このAPIは間違ったコンテキストの引数でアクセスされました」という結果になります。 TargetInvocationExceptionで。
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);
" model"という名前のオブジェクトは現在のスレッドのコンテキストにありません。どうすれば修正できますか?モデルをDispatcherのコンテキストに取得する方法はありますか? または、これを行う方法はここに行く方法ではありませんか?
解決
これは、ビューポートに追加するシーンオブジェクトを生成/変更して、別のスレッドからそのビューポートがインスタンス化されたときに発生します。簡単な回避策があります。ビューポートオブジェクトを更新するコードを関数にカプセル化します。次のスニペットを挿入すると完了です。
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