我正在开发一个项目,其中所有 DB 逻辑(读取和写入)都包含以下内容:
using(Util.DbRun ()) {
// Code here
}
我去查找了这个 DbRun 方法,发现了这个:
static readonly object dbWait = new object();
static public IDisposable DbRun ()
{
Monitor.Enter (dbWait);
return new Disposable (() => Monitor.Exit(dbWait));
}
class Disposable : IDisposable
{
private Action action;
private volatile bool disposed = false;
public Disposable (Action action)
{
if (action == null)
throw new ArgumentNullException ("action can't be null");
this.action = action;
}
#region IDisposable implementation
public void Dispose ()
{
bool run = false;
if (!disposed) {
lock (this) {
if (!disposed) {
run = true;
disposed = true;
}
}
}
if (run)
action ();
}
#endregion
}
我的问题是;这与一般lock { /* code here */ }
构造相比如何?