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);
Monitor.Enterat the beginning of the block andMonitor.Exitat the end. Thelockkeyword is just syntactical sugar that gets transformed into Monitor calls by the compiler.