Click here to Skip to main content
15,896,497 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi Friends,

I have designed a small tool in WPF, which contains two forms. The first form performs a huge task in a button click event. Due to this process, the UI is non-responsive. To over come this issue, I have gone for Threading concept.

Problem: After performing this huge task, I am calling Form2, which contains a "DocumentViewer". Since, the Form2 is called from the Form1 through a thread, the Default Printing is not working.

Error Message: "The calling thread cannot access thi object because a different thread owns it"

Please suggest some workaround to avoid this issue.

Thanks in advance,
Regards,
Suresh Kumar.B
Posted
Updated 9-May-12 23:26pm
v2

That's because the UI thread owns the UI elements.


In order to upadte the UI from another thread, you can use the Dispatcher, as explained in this link: http://www.switchonthecode.com/tutorials/working-with-the-wpf-dispatcher[^].

 
Share this answer
 
All WPF objects are really dependency objects, so they they can only be messed with in the thread that they were created in (because that's the thread that owns them). What you need to do is separate the logic of the task form the UI. This means that you cannot access any dependency properties from your background thread. What I usually do, is grab the values of the dependency properties I'm interested in, and pass them on in an object array to the background thread when I first start the process.

That being said, if you are working with a collection of objects in a ListBox (or something like that) than you may want to re-think how you're doing your UI. This is what binding is for. You place your collection of non-DependencyObjects in an ObservableCollection that is being held in a non-DependencyProperty. Then you bind the ItemsSource property of you ListBox like object to that collection. This way, you will be able to read from your collection. Yet, to insert into the collection, you will have to do that from the owning thread (changes to the collection will update the ListBox through the binding, which you're only allowed to do from the ListBox's owning thread). There are ways to use the owning threads Dispatcher to break that down into smaller components to keep the thread from freezing.
 
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