如何使用MVVM处理WPF中的跨线程异常 [英] How to handle cross thread exception in WPF with MVVM

查看:332
本文介绍了如何使用MVVM处理WPF中的跨线程异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我用MVVM模式开发WPF应用程序并获得跨线程异常。如何在没有调度程序的情况下处理跨线程异常。请帮助我解决问题。

Hi,

I have developing WPF application with MVVM pattern and getting cross thread exception. How to handle cross thread exception without dispatcher. Kindly help me for the solutions.

推荐答案

没有Dispatcher,只有一种合法的解决方法:不调用与活动UI的方法和属性相关的任何内容从UI线程以外的任何地方。如果您想要从任何非UI线程触发任何UI效果或查询,这可以通过Dispatcher完成。



您无法从非UI调用与UI相关的任何内容线。相反,您需要使用 Invoke System.Windows.Threading的方法。 Dispatcher (对于Forms或WPF)或 System.Windows.Forms.Control (仅限表单)。



您将在我过去的答案中找到有关其工作原理和代码示例的详细说明:

Control.Invoke()与Control.BeginInvoke()

使用Treeview扫描仪和MD5的问题



另请参阅有关线程的更多参考资料:

如何在vb.net中的另一个线程上运行keydown事件

启用禁用+多线程后控制事件不会触发



请不要告诉我们你没有做任何违法行为跨线程操作。即使您没有在UI上执行此操作,也有其他对象不能容忍在不同的线程上使用它们。最好的解决方案通常是不进行那些跨线程操作。请记住,没有类似于UI线程可用的现成机制,因此,如果您仍需要跨线程操作,则需要自己创建此类机制。我的一篇文章可以让你清楚地了解这个问题:用于线程通信和线程间调用的简单阻塞队列 [ ^ ]。



如需了解更多详情,请参阅我之前的回答:主线程上的.NET事件 [ ^ ]。



-SA
There is only one legitimate way of solving this problem without Dispatcher: not calling anything related to the methods and properties of the active UI from anywhere except the UI thread. If you want any UI effect or inquisition triggered from any non-UI thread, this is done through the Dispatcher.

You cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke(),
Problem with Treeview Scanner And MD5.

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net,
Control events not firing after enable disable + multithreading.

Please don't tell us that you did not do any illegal cross-thread operations. Even if you did not do it on UI, there are other objects which don't tolerate working with then on different threads. The best solution usually would be not doing those cross-thread operations. Remember that there is no a ready-to-use mechanism similar to the one available for UI threads, so, if you still need cross-thread operations, you will need to create such mechanism by yourself. One of my articles can give you the clear idea on hot to approach this problem: Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^].

For further detail, please see also my past answer: .NET event on main thread[^].

—SA


这篇关于如何使用MVVM处理WPF中的跨线程异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆