WPF 4.5对于多线程下的绑定支持

WPF数据绑定对于多线程的支持一直都没什么具体计划。当对象在非UI线程上发出了属性变化事件时,数据绑定基础设施就会对其作出响应。通常这是可行的,但因为潜在的竞态条件,这么做并不是真正安全的。从计算机科学的视角来看,禁用跨线程的访问是更为正确的做法,因为这才是导致集合变化事件的根源。

但遗憾的是,开发者并不总是在意正确性,他们只是想把事情做完。这样,他们会使用各种“线程安全”或是“分发安全”的可观测集合。在所有这些做法中,基本的设计就是在调用前将集合变化的事件编排到正确的线程中。在这种情况下,正确的线程就是分发者所运行的那个线程。但遗憾的是,这么做并未消除竞态条件的可能性。

在WPF 4.5中,微软向开发者提供了一种更为安全的解决方案。通过调用BindingOperations.EnableCollectionSynchronization,WPF数据绑定引擎会使用锁。其默认行为是获得前述调用所指定对象上的锁,但你也可以使用更为复杂的锁模式。但遗憾的是,这种方式很容易出错;对于后台线程来说,你很容易忘记获得集合的锁。当集合不再需要时,你还可能忘记禁用集合同步,这会导致内存泄露。

该技术的另一个问题是它并不会保护单个对象。这样当在锁下读取集合时,集合中每一项的属性就不一定能够保证会被安全读取。这对于复杂的getters以及无法以原子方式进行设置的属性来说极易产生问题(比如说大的值类型)。

我们强烈建议使用后台线程的开发者只使用集合中的不变对象来更新集合。如果对象无法保证是不变的,那么至少在确保属性getters的线程安全上要格外小心。当向集合中添加对象时,你最好不要使用该特性,而是将集合更新编排到UI线程中。

The #1 WPF Book--Now Updated for WPF 4! Full Color: Code samples appear as they do in Visual Studio! Thorough, authoritative coverage, practical examples, clear writing, and full-color presentation make this one of the most widely acclaimed programming books of the last decade. Windows Presentation Foundation (WPF) is the recommended technology for creating Windows user interfaces, giving you the power to create richer and more compelling applications than you dreamed possible. Whether you want to develop traditional user interfaces or integrate 3D graphics, audio/video, animation, dynamic skinning, multi-touch, rich document support, speech recognition, or more, WPF enables you to do so in a seamless, resolution-independent manner. WPF 4 Unleashed is the authoritative book that covers it all, in a practical and approachable fashion, authored by WPF guru and Microsoft developer Adam Nathan. * Covers everything you need to know about Extensible Application Markup Language (XAML) * Examines the WPF feature areas in incredible depth: controls, layout, resources, data binding, styling, graphics, animation, and more * Highlights the latest features, such as multi-touch, text rendering improvements, XAML language enhancements, new controls, the Visual State Manager, easing functions, and much more * Delves into topics that aren't covered by most books: 3D, speech, audio/video, documents, effects * Shows how to create popular UI elements, such as Galleries, ScreenTips, and more * Demonstrates how to create sophisticated UI mechanisms, such as Visual Studio-like collapsible/dockable panes * Explains how to create first-class custom controls for WPF * Demonstrates how to create hybrid WPF software that leverages Windows Forms, DirectX, ActiveX, or other non-WPF technologies * Explains how to exploit new Windows 7 features, such as Jump Lists and taskbar customizations
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值