I've come across this exception before:
The calling thread cannot access this object because a different thread owns it.
Usually it's been caused by event handlers that have asynchronous methods. And to fix this problem, in the past, usually all I've had to do is change something like this:
myObject.CustomEvent += MyCustomEventHandler;
To something like this:
myObject.CustomEvent += (s, e) => Dispatcher.Invoke(() => MyCustomEventHandler(s, e));
And that's all well and good when all of this code lives within the same WPF application. However, my solution is split up into multiple projects, one of which is a generic "Utilities" library that has some common functions I use frequently. In this library, I have a special "Timer" class that is a wrapper for executing a given method on a regular interval.
So it's got code that looks like this:
timer.Elapsed += OnTimedEvent;
I tried to change it to this, as I was used to doing:
timer.Elapsed += (s, e) => Dispatcher.Invoke(() => OnTimedEvent(s, e));
However, that wouldn't compile. It says:
Cannot access non-static method 'Invoke' in a static context
So, I think that Dispatcher
is somehow an alias for the current dispatcher inside of a WPF application, but not otherwise? (Or something like that?) So my next attempt was to change the code to this:
timer.Elapsed += (s, e) => Dispatcher.CurrentDispatcher.Invoke(() => OnTimedEvent(s, e));
That does compile, thankfully. However, it doesn't solve my problem. I'm still seeing those nasty InvalidOperationExceptions with the same message as before:
The calling thread cannot access this object because a different thread owns it.
So I successfully accomplish nothing by adding CurrentDispatcher. I must confess that I have a bit of a knowledge gap when it comes to some of this threading stuff, so any counsel you can offer is much appreciated!