Click here to Skip to main content
15,880,405 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
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.
Posted
Updated 5-Jun-15 4:22am
v2
Comments
[no name] 5-Jun-15 10:16am    
Okay so stop trying to access UI elements from the non UI thread.
[no name] 5-Jun-15 11:08am    
Hi Wes Aday,

I am not acessing the UI elements directly
Sergey Alexandrovich Kryukov 5-Jun-15 11:55am    
How do you know you don't?
Why "without Dispatcher"? It just makes no sense.
—SA

1 solution

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
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900