Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access object from another thread

I understand that this has been discussed on other questions but I am pulling my hair out here- clearly missing something obvious. I'll try to give you some background info so here goes...

I have a UI thread which was freezing up so I created a background worker to do all the heavy processing to keep my UI interactive.

I need to generate coordinates for some arcs/ paths which I then draw on a canvas. The background worker processes and runs it's work completed method where it stores the PathGeometry along with some other data in a list. I then called an update() method in my UI thread, from my backgroundworker, using the object I passed into the backgroundworker.

My problem is that when I begin to build the Path objects in the UI thread (it wouldn't let me build them in the backgroundworker thread) I am unable to access the PathGeometries. My object is a CommunicationArc and it holds the PathGeometry, opacity, colour etc.

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

I can access other parts of the object but not the PathGeometry and I do not know why. The backgroundworker surely has finished as the workcomplete method has run and the Arcs are all stored in my list. I simply want to read the arcs in my UI thread, process them a little bit more and go on to draw them.

I have tried using the Dispatcher from my UI thread like so:

arc.pathGeometry.Dispatcher.BeginInvoke((Action)(() =>
            {
                MessageBox.Show(arc.pathGeometry.ToString());
            }));

But I'm not really sure if what I am doing is right and various methods to call the Dispatcher either don't do anything or lock everything on the BeginInvoke().

Any help would be great, I feel like I'm going in circles here!

like image 749
user1842853 Avatar asked Mar 06 '26 11:03

user1842853


2 Answers

You need to create and manipulate your geometry objects directly on the UI thread. Any thread processing you perform cannot access the geometry object directly they must be dispatched to the thread which created them - the UI thread.

like image 69
Simon Wood Avatar answered Mar 09 '26 02:03

Simon Wood


You are creating PathGeometry objects on background thread, so arc.pathGeometry.Dispatcher will gives you Dispatcher of the background thread, not of UI thread.

You need to put your processing on UI dispatcher which you can do like this -

App.Current.Dispatcher.BeginInvoke((Action)(() =>
{
    MessageBox.Show(arc.pathGeometry.ToString());
}));
like image 43
Rohit Vats Avatar answered Mar 09 '26 02:03

Rohit Vats



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!