c# - 为什么 WPF 中的 UI 控件具有线程亲和性?

标签 c# wpf

为什么创建控件的线程是可以更新它的线程?为什么 MS 没有让人们能够使用锁定和其他线程同步技术来读取和写入具有多线程的 UI 控件上的属性。

最佳答案

每个 MSDN 的简短描述是

WPF’s threading model was kept in sync with the existing User32 threading model of single threaded execution with thread affinity. The primary reason for this was interoperability – systems like OLE 2.0, the clipboard, and Internet Explorer all require single thread affinity (STA) execution

较长的描述是这样的:

Most objects in WPF derive from DispatcherObject, which provides the basic constructs for dealing with concurrency and threading. WPF is based on a messaging system implemented by the dispatcher. This works much like the familiar Win32 message pump; in fact, the WPF dispatcher uses User32 messages for performing cross thread calls.

There are really two core concepts to understand when discussing concurrency in WPF – the dispatcher and thread affinity.

During the design phase of WPF, the goal was to move to a single thread of execution, but a non-thread "affinitized" model. Thread affinity happens when a component uses the identity of the executing thread to store some type of state. The most common form of this is to use the thread local store (TLS) to store state. Thread affinity requires that each logical thread of execution be owned by only one physical thread in the operating system, which can become memory intensive. In the end, WPF’s threading model was kept in sync with the existing User32 threading model of single threaded execution with thread affinity. The primary reason for this was interoperability – systems like OLE 2.0, the clipboard, and Internet Explorer all require single thread affinity (STA) execution.

Given that you have objects with STA threading, you need a way to communicate between threads, and validate that you are on the correct thread. Herein lies the role of the dispatcher. The dispatcher is a basic message dispatching system, with multiple prioritized queues. Examples of messages include raw input notifications (mouse moved), framework functions (layout), or user commands (execute this method). By deriving from DispatcherObject, you create a CLR object that has STA behavior, and will be given a pointer to a dispatcher at creation time.

您可以阅读全文 here

我个人更喜欢 WPF 的单线程模型,而不是必须使用锁定和线程同步技术。 Dispatcher可用于将消息传递到位于 different priority levels 的主 UI 线程,它负责处理大部分小型后台进程,如果您需要任何繁重的处理,您仍然可以为此创建自己的后台线程。

关于c# - 为什么 WPF 中的 UI 控件具有线程亲和性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8733303/

相关文章:

c# - 如何使用 C# 访问 Outlook 用户的日历?

c# - SignalR 2.1.0 预览版 2 最终更新到 2.1.0 rc1 最终在执行 services.AddSignalR() 时抛出 FileNotFoundException

c# - Serilog MSSqlServer 接收器是否应该与 Azure SQL Server 一起使用?

wpf - 在 IE9 中禁用 Cleartype(文本抗锯齿)

WPF 和 MVVM - 动态改变主题

wpf - 如何在 WPF 中获取此窗口布局?

c# - 使用脚本管理器显示弹出窗口

c# - 输入不是有效的 Base64 字符串,因为它包含非 base 64 字符

c# - XAML 在不改变颜色的情况下改变背景不透明度

wpf - 将 DataGrid 行中的 DoubleClick 命令绑定(bind)到 VM