I have a WPF app that makes use of some multi threading. I am curious to know if calling into the UI thread by using the Dispatcher.BeginInvoke() method considered thread-safe? Normally i would use the lock statement to make sure only one thread can access a variable. Would the following be thread-safe in a WPF app?
this.Dispatcher.BeginInvoke(() =>
{
_counter ++;
});
BeginInvoke is documented as thread safe (in fact, BeginInvoke , EndInvoke , Invoke , InvokeRequired , and CreateGraphics are).
BeginInvoke(DispatcherPriority, Delegate, Object) Executes the specified delegate asynchronously at the specified priority and with the specified argument on the thread the Dispatcher is associated with.
Note: the dispatcher is not itself a thread! Core can only do one thing at a time.
A dispatcher is often used to invoke calls on another thread. An example would be if you have a background thread working, and you need to update the UI thread, you would need a dispatcher to do it.
The Dispatcher.BeginInvoke
method will run its callback on the Dispatcher thread (typcially the UI thread, unless you have multiple Dispatchers)
Therefore, if you only use the counter
variable on the UI thread, you will have no threading issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With