【发布时间】:2014-06-01 00:29:07
【问题描述】:
在我尝试了很多很多解决方案之后,我无论如何都无法解决这个问题,所以我开始相信这个问题没有解决方案。
我有一个包含复杂属性的对象。例如: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;
}));
}
当我尝试从 GUI 访问 MainModules 类中的 faceModuleOutput 时,我得到了 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.
【问题讨论】:
-
InvalidOperationException的 excat 消息是什么? -
检查异常以获取有关正在发生的无效事情的更多详细信息
-
调用线程无法访问该对象,因为另一个线程拥有它
-
等等,这是您要访问的 UI 元素吗?
-
是的,我正在尝试将从工作线程返回的对象分配给 UI 元素
标签: c# wpf multithreading backgroundworker