Sysnet.Common/ActionOnDispose.cs
(开头部分) 2KB这里只显示每个文件的开头 60 行。登录后可以解锁完整代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Sysnet.Common
{
/// <summary>
/// Provides a wrapper over <see cref="IDisposable"/> that
/// invokes the provided delegate when <see cref="IDisposable.Dispose()"/>
/// is called.
/// </summary>
/// <example>
/// <code>
/// SqlConnection conn = new SqlConnection(connectionString);
/// using(new ActionOnDispose(new Action(conn.Close))
/// {
/// // Do work here...
/// // For cases where you want the connection closed
/// // but not disposed
/// }
/// </code>
/// </example>
public sealed class ActionOnDispose : IDisposable
{
/// <summary>
/// Creats a new <see cref="ActionOnDispose"/>
/// using the provided <see cref="Action"/>.
/// </summary>
/// <param name="unlockAction">
/// The <see cref="Action"/> to invoke when <see cref="Dispose"/> is called.
/// </param>
/// <exception cref="ArgumentNullException">if <paramref name="unlockAction"/> is null.</exception>
public ActionOnDispose(Action unlockAction)
{
Util.RequireNotNull(unlockAction, "unlockAction");
m_unlockDelegate = unlockAction;
}
/// <summary>
/// Calls the provided Action if it has not been called;
/// otherwise, throws an <see cref="Exception"/>.
/// </summary>
/// <exception cref="Exception">If <see cref="Dispose()"/> has already been called.</exception>
public void Dispose()
{
Action action = Interlocked.Exchange(ref m_unlockDelegate, null);
if (action != null)
{
action();
}
else
{
throw new InvalidOperationException("Cannot call Dispose() on this object more than once..");
}
}
后面还有 8 行代码,购买后查看完整代码
24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明
AI 解读
登录后可用,每次 10 积分,解读结果公开显示在下面。
还没有人解读过这个文件。
