我有两个不同的进程(托管WCF服务的w3wp.exe和我自己的自定义Windows服务),它们都执行复杂的数据库任务,该任务应具有序列化访问权限以防止无效状态。 (正在执行的任务分为三步:1。从数据库中获取信息,2。验证信息.3。如果信息正常,则INSERT - 因此需要独占的顺序操作。
因此代码是:
public static class Arbiter {
public static void AddEntry(Database db, Entry entry) {
Eligibility canAdd = db.GetAddEligibility( entry );
if( canAdd ) {
db.AddEntry( entry );
}
}
}
此代码不是线程安全的,并且在多个进程中执行,因此我应该使用Mutex
,但应该如何维护?我看到两个选择:
public static class Arbiter {
private static readonly Mutex mutex = new Mutex( false, @"Global\Foobarbaz" );
public static void AddEntry(Database db, Entry entry) {
if( !mutex.WaitOne( 3000 ) ) {
throw new TimeoutException("Mutex wasn't released.");
}
try {
Eligibility canAdd = db.GetAddEligibility( entry );
if( canAdd ) {
db.AddEntry( entry );
}
} finally {
mutex.ReleaseMutex();
}
}
}
public static class Arbiter {
public static void AddEntry(Database db, Entry entry) {
using( Mutex mutex = new Mutex( true, @"Global\Foobarbaz" ) ) {
if( !mutex.WaitOne( 3000 ) ) {
throw new TimeoutException("Mutex wasn't released.");
}
try {
Eligibility canAdd = db.GetAddEligibility( entry );
if( canAdd ) {
db.AddEntry( entry );
}
} finally {
mutex.ReleaseMutex(); // this is necessary as Mutex.Dispose does not release the mutex.
}
}
}
哪种方法更合适?