Multithreading and WPF 4.5
WPF 4.5 has improved its support for multi-threaded data binding, but the technique is still risky. This report attempts to explain how it works and what’s involved in using it safely.
WPF data binding has always had haphazard support for multi-threading. When an object raises a property changed event on a non-UI thread the data binding infrastructure is kicked into gear. And generally this works, though it isn’t really safe because of potential race conditions. From a computer science perspective it would be more correct to simply disallow cross-thread access, which is actually the case for the collection changed event.
Unfortunately developers don’t always care about correctness, they just want to get something done. So end up with various attempts at a “thread-safe” or “dispatcher-safe” observable collection. In all these attempts the fundamental design is to marshal the collection-changed event to the correct thread before invoking it. In this case the correct thread is whichever one that the dispatcher is running on. Unfortunately this doesn’t eliminate the possibility of a race condition.
With WPF 4.5, Microsoft is offering developers a much safer alternative. By calling BindingOperations.EnableCollectionSynchronization, the WPF data binding engine participates in locking. The default behavior is to acquire a lock on the object specified in the aforementioned call, but you also have the option to use more complex locking schemes. Unfortunately this is an error prone technique; it is easy to forget to acquire the collection’s lock while on the background thread. You can also forget to disable the collection synchronization when the collection is no longer needed, which could create a memory leak.
Another problem with this technique is that it doesn’t protect individual objects. So while the collection is being read under a lock, properties on each item in the collection are not necessarily being safely read. This is mostly a problem for complex getters and properties that cannot be set atomically (e.g. large value types).
We highly recommend that anyone using a background thread to update a collection only use immutable objects in that collection. Or if the objects cannot be made immutable, extreme care should be taken to at least make their property getters thread-safe. And when push comes to shove, you are probably better off forgetting that this feature exists and just marshal your collection updates to the UI thread.
Not supported on silverlight
Tiago Romero Garcia Mar 01, 2015