2

When we use the lock statement, it is essentially doing a Monitor.Enter at the beginning of the locking block and a Monitor.Exit at the end of the block. This process is automatically handled by the runtime.

A similar behaviour is at the end of the using block, it calls the Dispose method of IDisposable.

My question is, that if there is a way to call a method in the disposable object automatically at the beginning of the using block.

The reason I want to do this is that, I have implemented a custom ObservableCollection<T> that has 2 extra methods: BeginUpdate and EndUpdate. They are used to signal a batch update process. The collection won't raise the collection changed event until EndUpdate is called.

Although it's perfectly fine to call the 2 methods manually at the beginning and end of the batch process, but it'd be really nice if I can do something like this:

using(myCollection)
  foreach(var item in anotherBigList)
    myCollection.Add(item);
  • 1
    It's exactly doing a Monitor.Enter at the beginning of the block and Monitor.Exit at the end. The lock keyword is just syntactical sugar that gets transformed into Monitor calls by the compiler. – Craig Jun 25 '15 at 6:54
8

First I don't like using IDisposable on actual collection. It muddles the actual meaning of Disposable.

I would do it like this:

public class CollectionUpdateContext<T>: IDisposable // can also be inner class of custom collection
{
    public CollectionUpdateContext(ObservableCollection<T> inner)
    {
        inner.BeginUpdate();
    }

    public Dispose()
    {
        inner.EndUpdate();
    }
}

public class CustomCollection<T> : ObservableCollection<T>
{
    // whatever code of custom collection

    CollectionUpdateContext<T> Updating() // this can be also as extension method
    {
        return new CollectionUpdateContext<T>(this);
    }
}

using(myCollection.Updating())
  foreach(var item in anotherBigList)
    myCollection.Add(item);

This way, it is clear that the using block is related to update mechanics of your collection. Also, because the IDisposable is not in custom collection, it forces programmer to call the Updating method. And lastly, it doesn't muddle the custom collection by adding IDisposable, that has different meaning.

  • ? While I understand the intention of your example, how/where is CollectionUpdateContext<T>.UpdatingCollection being called? Did you perhaps intend UpdatingCollection to be the constructor of CollectionUpdateContext<T>? – Marjan Venema May 22 '15 at 17:59
  • @MarjanVenema Sorry, yes. I didn't try to run the code, so I couldn't get compiler do the check. – Euphoric May 24 '15 at 18:35
  • this seems like abusing the using mechanism... – AK_ May 25 '15 at 10:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.