【发布时间】:2010-04-05 20:08:10
【问题描述】:
这是场景:
我有一个名为 Transaction 的对象,它需要确保在任何给定时间只有一个实体有权编辑它。
为了便于长期锁定,我让类生成一个可用于进行编辑的令牌对象。
你会这样使用它:
var transaction = new Transaction();
using (var tlock = transaction.Lock())
{
transaction.Update(data, tlock);
}
现在,我希望TransactionLock 类实现IDisposable,以便清楚其用法。但是,我没有任何非托管资源可供处置。然而,TransctionLock 对象本身是一种“非托管资源”,因为 CLR 不知道如何正确完成它。
所有这一切都很好,花花公子,我只需使用 IDisposable 就可以了。
但是,当我尝试在终结器中执行此操作时,我的问题出现了:
~TransactionLock()
{
this.Dispose(false);
}
如果可能,我希望终结器从锁定中释放事务。 如何在终结器中检测父事务 (this.transaction) 是否已完成?
我应该使用更好的模式吗?
另外,Transaction 类本身不必是一次性的,因为它不维护对锁的引用,也不关心它在进入坟墓时是否被解锁。
Transaction 类看起来像这样:
public sealed class Transaction
{
private readonly object lockMutex = new object();
private TransactionLock currentLock;
public TransactionLock Lock()
{
lock (this.lockMutex)
{
if (this.currentLock != null)
throw new InvalidOperationException(/* ... */);
this.currentLock = new TransactionLock(this);
return this.currentLock;
}
}
public void Update(object data, TransactionLock tlock)
{
lock (this.lockMutex)
{
this.ValidateLock(tlock);
// ...
}
}
internal void ValidateLock(TransactionLock tlock)
{
if (this.currentLock == null)
throw new InvalidOperationException(/* ... */);
if (this.currentLock != tlock)
throw new InvalidOperationException(/* ... */);
}
internal void Unlock(TransactionLock tlock)
{
lock (this.lockMutex)
{
this.ValidateLock(tlock);
this.currentLock = null;
}
}
}
以及TransactionLock 的Dispose(bool) 代码:
private void Dispose(bool disposing)
{
if (disposing)
{
if (this.Transaction != null)
{
this.Transaction.Unlock(this);
this.Transaction = null;
}
}
}
【问题讨论】:
-
在什么情况下
TransactionLock可以在没有Dispose被调用的情况下被实际放弃?我看不出终结器能够做任何有用的事情。
标签: c# .net dispose idisposable