Code Analysis CA1063 fires when deriving from IDisposable and providing implementation in base class

This is a false positive due to a minor bug in the rule itself. When trying to figure out if a class re-implements IDisposable (after figuring out that there’s a base class implementation that could be overridden), it only looks at whether the class’ interfaces include IDisposable. Unfortunately, the interface list that shows up in …

Read more

What is the correct way of adding thread-safety to an IDisposable object?

I tend to use an integer rather than a boolean as your field for storing the disposed status, because then you can use the thread-safe Interlocked class to test if Dispose has already been called. Something like this: private int _disposeCount; public void Dispose() { if (Interlocked.Increment(ref _disposeCount) == 1) { // disposal code here …

Read more

Do I need to Dispose a SemaphoreSlim?

If you access the AvailableWaitHandle property, then Yes, you must call Dispose() to cleanup unmanaged resources. If you do not access AvailableWaitHandle, then No, calling Dispose() won’t do anything important. SemaphoreSlim will create a ManualResetEvent on demand if you access the AvailableWaitHandle. This may be useful, for example if you need to wait on multiple …

Read more

Intercepting an exception inside IDisposable.Dispose

You can extend IDisposable with method Complete and use pattern like that: using (MyWrapper wrapper = new MyWrapper()) { throw new Exception(“Bad error.”); wrapper.Complete(); } If an exception is thrown inside the using statement Complete will not be called before Dispose. If you want to know what exact exception is thrown, then subscribe on AppDomain.CurrentDomain.FirstChanceException …

Read more

Manually destroy C# objects

You don’t manually destroy .Net objects. That’s what being a managed environment is all about. In fact, if the object is actually reachable, meaning you have a reference you can use to tell the GC which object you want to destroy, collecting that object will be impossible. The GC will never collect any object that’s …

Read more

Combining foreach and using

foreach (ManagementObject result in results) using(result) { //code here } It’s not normally good practice to assign the variable outside the using block because the resource would be disposed but could stay in scope. It would, however, result in clearer code here because you can nested the using statement against the foreach. EDIT: As pointed …

Read more