在WPF中是UI dispatcher.begininvoke方法线程安全吗?

时间:2021-05-06 20:57:53

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?

我有一个WPF应用程序,它使用了一些多线程。我很想知道是否通过使用被认为是线程安全的Dispatcher.BeginInvoke()方法调用UI线程?通常我会使用lock语句来确保只有一个线程可以访问变量。以下是WPF应用程序中的线程安全吗?

this.Dispatcher.BeginInvoke(() =>
{
    _counter ++;
});

1 个解决方案

#1


6  

The Dispatcher.BeginInvoke method will run its callback on the Dispatcher thread (typcially the UI thread, unless you have multiple Dispatchers)

Dispatcher.BeginInvoke方法将在Dispatcher线程上运行其回调(通常是UI线程,除非你有多个Dispatchers)

Therefore, if you only use the counter variable on the UI thread, you will have no threading issues.

因此,如果仅在UI线程上使用计数器变量,则不会出现线程问题。

#1


6  

The Dispatcher.BeginInvoke method will run its callback on the Dispatcher thread (typcially the UI thread, unless you have multiple Dispatchers)

Dispatcher.BeginInvoke方法将在Dispatcher线程上运行其回调(通常是UI线程,除非你有多个Dispatchers)

Therefore, if you only use the counter variable on the UI thread, you will have no threading issues.

因此,如果仅在UI线程上使用计数器变量,则不会出现线程问题。