I came across this implementation of disposable pattern provided by microsoft: https://msdn.microsoft.com/en-us/library/system.idisposable(v=vs.110).aspx
using System;
class BaseClass : IDisposable
{
// Flag: Has Dispose already been called?
bool disposed = false;
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing) {
// Free any other managed objects here.
//
}
// Free any unmanaged objects here.
//
disposed = true;
}
~BaseClass()
{
Dispose(false);
}
}
Let's say I have a C++ class that is associated to this C# class, and I want to delete
C++ object on disposing C# class to make sure that my unmanaged resources are released properly. I add a function DestructNative(self)
which basically makes a native C++ call delete (CppObject*)self
on associated C++ object. So my code looks like this:
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing) {
// Free any other managed objects here.
//
}
DestructNative(self);
disposed = true;
}
So my question is, knowing that C# finalizers can be called from a different thread, do I need to provide synchronization inside C++ object's destructor to make sure I don't have any race conditions when Dispose(false)
called from C# finalizer?
Additional question
Is microsoft disposable pattern broken? Seems like disposed
flag is a simple variable which is not synchronized if finalizer is called from a different thread.