wpfmultithreadingdispatcher

Locking dispatcher


Is it necessary to lock code snippet where multiple threads access same wpf component via dispatcher?

Example:

void ladder_OnIndexCompleted(object sender, EventArgs args)
{
    lock (locker)
    {
        pbLadder.Dispatcher.Invoke(new Action(() => { pbLadder.Value++; }));
    }
}

pbLadder is a progress bar and this event can be raised from multiple threads in the same time.


Solution

  • You should not acquire a lock if you're then going to marshal to another thread in a synchronous fashion - otherwise if you try to acquire the same lock in the other thread (the dispatcher thread in this case) you'll end up with a deadlock.

    If pbLadder.Value is only used from the UI thread, then you don't need to worry about locking for thread safety - the fact that all the actions occur on the same thread isolates you from a lot of the normal multi-threading problems. The fact that the original action which caused the code using pbLadder.Value to execute occurred on a different thread is irrelevant.