[英]Adding a child to Viewport3D asynchronously gives “This API was accessed with arguments from the wrong context.”
當我嘗試將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);
似乎名為“模型”的對象不在當前線程的上下文中。 我怎樣才能解決這個問題? 有沒有一種方法可以使模型適應分派器的環境? 還是這種方式不是去這里的方式?
每當您生成/修改場景對象以從實例化一個Viewport的另一個線程生成/修改場景對象以將其添加到Viewport時,就會發生這種情況。 有一個簡單的解決方法。 將將視口對象更新的代碼封裝到一個函數中。 插入以下代碼片段,即可完成操作。
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.