145 lines
3.4 KiB
C#
145 lines
3.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
|
|
namespace JD.Kernel.Classes
|
|
{
|
|
/// <summary>
|
|
/// Simple class that implements IDisposable using a delegate.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Can be useful to implement a "using pattern" without defining a nested class.
|
|
/// </remarks>
|
|
/// <example>
|
|
/// <code>
|
|
/// public class MyClass
|
|
/// {
|
|
/// public IDisposable Start()
|
|
/// {
|
|
/// return new DisposableHelper(delegate
|
|
/// {
|
|
/// // ... End code.
|
|
/// });
|
|
/// }
|
|
/// }
|
|
///
|
|
/// using (MyClass.Start())
|
|
/// {
|
|
/// ...
|
|
/// }
|
|
/// </code>
|
|
/// </example>
|
|
public class DisposableHelper : IDisposable
|
|
{
|
|
private Action m_disposeAction;
|
|
|
|
/// <summary>
|
|
/// Ctor.
|
|
/// </summary>
|
|
/// <param name="disposeAction">Action to execute on dispose (if null, empty action).</param>
|
|
public DisposableHelper(Action disposeAction)
|
|
{
|
|
m_disposeAction = disposeAction;
|
|
}
|
|
|
|
#region IDisposable Members
|
|
|
|
/// <summary>
|
|
/// Executes its dispose operation.
|
|
/// </summary>
|
|
[DebuggerStepThrough]
|
|
public void Dispose()
|
|
{
|
|
Action disposeAction = m_disposeAction;
|
|
m_disposeAction = null;
|
|
|
|
if (disposeAction != null)
|
|
{
|
|
disposeAction();
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Functions
|
|
|
|
/// <summary>
|
|
/// Disposes the value if not null.
|
|
/// </summary>
|
|
/// <param name="value"></param>
|
|
public static void SafeDispose(IDisposable value)
|
|
{
|
|
if (value != null)
|
|
{
|
|
value.Dispose();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Disposes the value if not null.
|
|
/// </summary>
|
|
/// <param name="list"></param>
|
|
public static void SafeDisposeList<T>(IEnumerable<T> list)
|
|
where T : IDisposable
|
|
{
|
|
if (list == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
foreach (var item in list)
|
|
{
|
|
SafeDispose(item);
|
|
}
|
|
}
|
|
|
|
public static void SafeDisposeAndClearList<T>(ICollection<T> list)
|
|
where T : IDisposable
|
|
{
|
|
if (list == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
foreach (var item in list)
|
|
{
|
|
SafeDispose(item);
|
|
}
|
|
|
|
list.Clear();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Disposes the value if not null.
|
|
/// </summary>
|
|
/// <param name="value"></param>
|
|
public static void SafeDispose<T>(T value)
|
|
where T : IDisposable
|
|
{
|
|
if (!Equals(value, null))
|
|
{
|
|
value.Dispose();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Disposes the value if not null and sets it to null.
|
|
/// </summary>
|
|
/// <param name="value"></param>
|
|
public static void SafeDispose<T>(ref T value)
|
|
where T : IDisposable
|
|
{
|
|
if (!Equals(value, null))
|
|
{
|
|
// value will still be default(T) even if implementation of Dispose accesses value!
|
|
T temp = value;
|
|
|
|
value = default(T);
|
|
|
|
temp.Dispose();
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
}
|