本文介绍了WPF中的线程错误(另一个线程拥有它。)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在尝试从WPF中的另一个类访问文本框。该方法由线程启动。当我尝试设置文本框值时会出现错误 WindowsBase.dll中出现未处理的System.InvalidOperationException类型异常 附加信息:调用线程无法访问此对象,因为另一个线程拥有它。 方法调用: 线程tScan = new 线程(MyClass.Start); 方法从MyClass.Start()方法调用的状态,例如, public static void StatusPrint() { Instance.txtReport.Text = 将在此处设置值。; } 因为我是WPF的新手所以,需要你的帮助来摆脱这个。 我尝试了什么: 我试过这样做。 public static void StatusPrint() { System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke( new ThreadStart(() = > Instance.txtReport.Text = value将在这里设置。)); } 这里实例是在MainWindow中声明的静态变量class已启动到此。 这里我没有收到任何运行时错误,但它只是没有执行。解决方案 为什么 ThreadStart 在 Dispatcher.CurrentDispatcher 中?您不想启动新线程。将 ThreadStart 更改为操作,它应该可以。 我有一个扩展名我喜欢在这种情况下使用的方法: public static void BeginInvokeIfRequired(此调度程序调度程序,操作操作) { if (operation == null ) return ; if (dispatcher.CheckAccess()) { action(); } else { dispatcher.BeginInvoke(action); } } 要调用它,您需要做的就是: Application.Current.Dispatcher.BeginInvokeIfRequired(()=> Instance.txtReport.Text = 将在此处设置值。); Hi,I am trying to access the textbox from another class in WPF. The method has been initiated by a thread. And when I am trying to set the textbox value it is getting an errorAn unhandled exception of type 'System.InvalidOperationException' occurred in WindowsBase.dllAdditional information: The calling thread cannot access this object because a different thread owns it.method called:Thread tScan = new Thread(MyClass.Start);method Statusprint called from MyClass.Start() method like,public static void StatusPrint() { Instance.txtReport.Text = "value will set here."; }As I am new in WPF so, need your help to get rid of this.What I have tried:I tried to do this way.public static void StatusPrint() { System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(new ThreadStart(() => Instance.txtReport.Text = "value will set here.")); }here Instance is a static variable declared in MainWindow class initiated to this.here I am not getting any runtime error but it is just not executing. 解决方案 Why ThreadStart inside the Dispatcher.CurrentDispatcher? You don't want to start a new thread. Change ThreadStart to Action and it should work.I have an extension method that I like to use in this case:public static void BeginInvokeIfRequired(this Dispatcher dispatcher, Action operation){ if (operation== null) return; if (dispatcher.CheckAccess()) { action(); } else { dispatcher.BeginInvoke(action); }}To call it, all you need to do is this:Application.Current.Dispatcher.BeginInvokeIfRequired(()=>Instance.txtReport.Text = "value will set here."); 这篇关于WPF中的线程错误(另一个线程拥有它。)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-14 23:45