WPF Dispatcher.Invoke 'hanging' WPF Dispatcher.Invoke 'hanging' wpf wpf

WPF Dispatcher.Invoke 'hanging'


Invoke is synchronous - you want Dispatcher.BeginInvoke. Also, I believe your code sample should move the "SetValue" inside an "else" statement.


I think this is better shown with code. Consider this scenario:

Thread A does this:

lock (someObject){   // Do one thing.   someDispatcher.Invoke(() =>   {      // Do something else.   }}

Thread B does this:

someDispatcher.Invoke(() =>{   lock (someObject)   {      // Do something.   }}

Everything might appear fine and dandy at first glance, but its not. This will produce a deadlock. Dispatchers are like queues for a thread, and when dealing with deadlocks like these its important to think of them that way: "What previous dispatch could have jammed my queue?". Thread A will come in...and dispatch under a lock. But, what if thread B comes in at the point in time at which Thread A is in the code marked "Do one thing"? Well...

  • Thread A has the lock on someObject and is running some code.
  • Thread B now dispatches, and the dispatcher will try to get the lock on someObject, jamming up your dispatcher since Thread A has that lock already.
  • Thread A will then queue up another dispatch item. This item will never be fired, because your dispatcher will never finish processing your previous request; its already jammed up.

You now have a beautiful deadlock.


You say you are creating a new STA thread, is the dispatcher on this new thread running?

I'm getting from "this.Dispatcher.Thread != Thread.CurrentThread" that you expect it to be a different dispatcher. Make sure that its running otherwise it wont process its queue.