New option for .NET 4.5
Starting with .NET 4.5, there is a built-in mechanism for automatically synchronizing access to collections and sending CollectionChanged events to the user interface stream. To enable this function, you need to call BindingOperations.EnableCollectionSynchronization from your UI thread.
EnableCollectionSynchronization does two things:
- It remembers the stream from which it is called, and causes the data binding pipeline to move
CollectionChanged events in that stream. - Gets the collection lock until the processed event is processed, so that the event handlers that trigger the UI thread will not try to read the collection when it is modified from the background thread.
It is very important, this does not take care of everything : to provide thread-safe access to an insecure collection , you need to cooperate by getting the same lock from the background threads when the collection is modified.
Therefore, to work properly, the following steps are required:
1. Decide which lock you will use.
This will determine which EnableCollectionSynchronization overload should be used. In most cases, a simple lock statement will suffice, so this overload is the standard choice, but if you use some kind of fantastic synchronization mechanism, there is also support for custom locks .
2. Create an assembly and enable synchronization
Depending on the lock mechanism selected, invoke the corresponding overload in the user interface thread . If you use the standard lock statement, you need to provide a lock object as an argument. If you use custom synchronization, you need to provide a CollectionSynchronizationCallback delegate and a context object (which may be null ). When invoked, this delegate should receive your custom lock, invoke the Action passed to it, and release the lock before returning.
3. Collaborate by locking the collection until it is modified
You must also lock the collection using the same mechanism when you intend to change it yourself; do this with lock() in the same lock object that was passed to EnableCollectionSynchronization in a simple script, or with the same custom synchronization mechanism in a user script.
Jon Jan 30 '13 at 10:46 2013-01-30 10:46
source share