0

I have a collection that has child collections and each of them can be updated from a different thread. How can I properly enable collection synchronization for all of them?

My current solution is to create an interface ISynchronized that expose the object to lock when the collection is accessed:

public interface ISynchronized : IEnumerable
{
    object SyncRoot { get; }
}

And then subscribe to BindingOperations.CollectionRegistering:

BindingOperations.CollectionRegistering += OnCollectionReg;

private void OnCollectionReg(object sender, CollectionRegisteringEventArgs e)
{
    if (e.Collection is ISynchronized synchronized)
    {
         BindingOperations.EnableCollectionSynchronization(synchronized, synchronized.SyncRoot);
    }
}

Are there pitfalls in this?

Orace
  • 7,822
  • 30
  • 45
Mike Waters
  • 109
  • 2
  • I don't see any pitfalls, and it looks good. You should put it as an answer to this question: [C# How to code EnableCollectionSynchronization for Collection of Collections](https://stackoverflow.com/questions/32403139/c-sharp-how-to-code-enablecollectionsynchronization-for-collection-of-collection) – Orace Jul 11 '22 at 09:09

1 Answers1

0

A possible issue is when a collection is bound multiple times.
The CollectionRegistering event will be thrown multiple times too.
And the BindingOperations.EnableCollectionSynchronization call will also be done multiple times for the same collection.
Altought, the documentation doesn't states if that is an issue.

Orace
  • 7,822
  • 30
  • 45