Files
Umbraco-CMS/src/Umbraco.Core/DisposableObject.cs

62 lines
1.7 KiB
C#
Raw Normal View History

2017-07-20 11:21:28 +02:00
using System;
namespace Umbraco.Core
{
2017-07-20 11:21:28 +02:00
/// <summary>
/// Abstract implementation of IDisposable.
/// </summary>
/// <remarks>
/// Can also be used as a pattern for when inheriting is not possible.
///
2015-07-14 15:55:56 +02:00
/// See also: https://msdn.microsoft.com/en-us/library/b1yfkh5e%28v=vs.110%29.aspx
/// See also: https://lostechies.com/chrispatterson/2012/11/29/idisposable-done-right/
///
2015-07-14 15:55:56 +02:00
/// Note: if an object's ctor throws, it will never be disposed, and so if that ctor
/// has allocated disposable objects, it should take care of disposing them.
2017-07-20 11:21:28 +02:00
/// </remarks>
public abstract class DisposableObject : IDisposable
{
private readonly object _locko = new object();
2017-07-20 11:21:28 +02:00
// gets a value indicating whether this instance is disposed.
2015-07-14 15:55:56 +02:00
// for internal tests only (not thread safe)
2017-07-20 11:21:28 +02:00
public bool Disposed { get; private set; }
2017-07-20 11:21:28 +02:00
// implements IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
2015-07-14 15:55:56 +02:00
// finalizer
2017-07-20 11:21:28 +02:00
~DisposableObject()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
// can happen if the object construction failed
if (_locko == null)
return;
2017-07-20 11:21:28 +02:00
lock (_locko)
{
if (Disposed) return;
Disposed = true;
}
2015-07-14 15:55:56 +02:00
DisposeUnmanagedResources();
2015-07-14 15:55:56 +02:00
if (disposing)
DisposeResources();
2017-07-20 11:21:28 +02:00
}
2017-07-20 11:21:28 +02:00
protected abstract void DisposeResources();
2017-07-20 11:21:28 +02:00
protected virtual void DisposeUnmanagedResources()
{ }
}
}