Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In WPF is the UI dispatcher.begininvoke method thread safe?

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 ++;
});
like image 382
Fixer Avatar asked Sep 12 '10 14:09

Fixer


People also ask

Is BeginInvoke thread safe?

BeginInvoke is documented as thread safe (in fact, BeginInvoke , EndInvoke , Invoke , InvokeRequired , and CreateGraphics are).

What is dispatcher BeginInvoke?

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.

Is dispatcher a thread?

Note: the dispatcher is not itself a thread! Core can only do one thing at a time.

What is dispatcher thread in WPF?

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.


1 Answers

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.

like image 83
SLaks Avatar answered Sep 24 '22 21:09

SLaks