Click here to Skip to main content
15,877,857 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello again.

I'm starting to use WPF and now I have a problem.

I need to do a TextBlock with the actual time. I tried specifying in the code:


But when execute the form appears this error:

The calling thread cannot access this object because a different thread owns it.

How I can show the now time?


See this to learn about the WPF threading model and accessing UI elements from threads other than the UI thread...

Threading Model[^]
Share this answer
Sergey Alexandrovich Kryukov 23-Jul-11 1:40am    
Makes sense, my 5. I provided more detailed explanation in my answer, please see.
Try using the Dispatcher as shown here[^].
Share this answer
Sergey Alexandrovich Kryukov 23-Jul-11 1:40am    
Correct, my 5. I provided more detailed explanation in my answer, please see.
More details to understand correct answer by Abhinav and Mark:

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[^],
Control events not firing after enable disable + multithreading[^].

Share this answer
Abhinav S 23-Jul-11 2:07am    
5 for the detailed explanation.
Sergey Alexandrovich Kryukov 23-Jul-11 2:16am    
Thank you, Abhinav.
TANicox 23-Jul-11 13:05pm    
Please you can specify an example with this? Because I'm novice and I don't understand so much
Mark Salsbery 23-Jul-11 18:53pm    
Something like this?

Textblock1.Dispatcher.BeginInvoke(new Action(() =>
Textblock1.Text = DateTime.Now.ToShortTimeString();
TANicox 23-Jul-11 19:14pm    
Yes! I did it differently, but I'll use this because it is more shorter

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