在我尝试了很多很多解决方案之后,我无法以任何方式解决这个问题,所以我开始相信这个问题没有解决方案。
我有一个包含复杂属性的对象。例如:List<SomeComplexObject>
.我正在工作线程上运行此类中的一个方法,以保持 GUI 运行直到工作线程完成。当它完成执行时,我想使用这些对象的属性来更新 GUI 比方说我想使用 List<SomeComplexObject>
遍历此列表并更新 GUI。但每次我尝试访问此列表时,调试器都会抛出一个 InvalidOperationException
: 调用线程无法访问此对象,因为另一个线程拥有它。
我试图让这个类的所有属性都可变,但没有希望我也使用了 Lazy<T>
类方法来解决,但出现同样的问题。
包含辅助函数的类:
public class MainModules
{
#region Attributes
public VIDEO video;
public string VideoPath
{
get;
set;
}
LowLevelModule lowLevelOutput;
//this list that I want to use to Update GUI
public volatile List<FaceRecognitionModule> faceModuleOutput;
//worker function running on different thread
public void RunMainModules()
{
//some complex work to set the class attributes
}
}
GUI类中的线程创建
private void RunMainModules_BtnClick(object sender, RoutedEventArgs e)
{
// MainModule = new MainModules(mainModuleObj, Inpath, lif, keyframefolderpath, trdbpath, labelspath, rrankspath, alignmatpath, 11, 10);
this.LazyMainModule = new Lazy<MainModules>(this.InitLazyMainModule);
MainModuleThread = new Thread(this.RunMainModules);
MainModuleThread.Start(MainModule);
}
public MainModules InitLazyMainModule()
{
return new MainModules(mainModuleObj, Inpath, lif, keyframefolderpath, trdbpath, labelspath, rrankspath, alignmatpath, 11, 10);
}
public void RunMainModules(Object obj)
{
//MainModules mm = obj as MainModules;
MainModules mm = LazyMainModule.Value;
mm.RunMainModules();
this.Dispatcher.Invoke((Action)(() =>
{
this.InitSpeechRec_Btn.IsEnabled = true;
}));
}
当我尝试访问 faceModuleOutput
时在类里面MainModules
从 GUI 我得到了 InvalidOperationException
.
Image img = new Image();
//InvalidOperationException occurs here
img.Source = LazyMainModule.Value.faceModuleOutput[0].keyframes[1].keyframe;
为了简要介绍这篇文章: 我想从主线程访问由后台线程实例化的对象,但它抛出
InvalidOperationException : The calling thread cannot access this object because a different thread owns it.
最佳答案
需要从 GUI 线程创建/修改 UI 控件。否则就是违法的。
MainModuleThread
似乎(至少)正在创建和修改 Image
。这应该在 GUI 线程中完成(调用 RunMainModules_BtnClick
的线程)
关于c# - 尝试从另一个线程访问复杂对象时出现 InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23975709/