这里是场景:我应该使用IDisposable进行纯管理资源吗?
我有一个对象叫Transaction
需要确保只有一个实体有权限在任何给定的时间编辑它。
为了促进长时间的锁定,我有类生成一个令牌对象,可用于进行编辑。
你会使用这样的:
var transaction = new Transaction();
using (var tlock = transaction.Lock())
{
transaction.Update(data, tlock);
}
现在,我希望TransactionLock
类来实现IDisposable
使得它的使用可以明确。但是,我没有任何非托管资源可供处理。然而,在CLR不知道如何正确定位它的意义上,TransctionLock对象本身就是一种“非托管资源”。
所有这一切都会很好,我会只使用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;
}
}
}
而且Dispose(bool)
代码为TransactionLock
:
private void Dispose(bool disposing)
{
if (disposing)
{
if (this.Transaction != null)
{
this.Transaction.Unlock(this);
this.Transaction = null;
}
}
}
在什么情况下可以了'TransactionLock'现实没有'已经在其名为Dispose'被抛弃?我看不到任何情况下终结者能够做任何有用的事情。 – supercat 2012-06-28 18:30:11