74 lines
No EOL
1.4 KiB
C#
74 lines
No EOL
1.4 KiB
C#
using System;
|
|
|
|
namespace JD.Kernel.Classes
|
|
{
|
|
/// <summary>
|
|
/// Owns a resource until ask to release.
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
public class SafeHandle<T> : IDisposable
|
|
where T : IDisposable
|
|
{
|
|
#region Variables
|
|
|
|
private T m_resource;
|
|
private bool m_disposeResource = true;
|
|
|
|
#endregion
|
|
|
|
#region Constructor
|
|
|
|
public SafeHandle(T handle)
|
|
{
|
|
m_resource = handle;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
if (m_disposeResource)
|
|
{
|
|
DisposableHelper.SafeDispose(m_resource);
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Properties
|
|
|
|
public T Resource
|
|
{
|
|
get
|
|
{
|
|
return m_resource;
|
|
}
|
|
set
|
|
{
|
|
Dispose();
|
|
m_resource = value;
|
|
m_disposeResource = true;
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Methods
|
|
|
|
public static implicit operator T(SafeHandle<T> handle)
|
|
{
|
|
return handle.m_resource;
|
|
}
|
|
|
|
public static implicit operator SafeHandle<T>(T resource)
|
|
{
|
|
return new SafeHandle<T>(resource);
|
|
}
|
|
|
|
public T Release()
|
|
{
|
|
m_disposeResource = false;
|
|
return m_resource;
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
} |