[英]Are there any loss in this alternative way of using c# Mutex class?
我有一個使用Mutex的應用程序(我沒有寫這個):
static void Main(string[] args)
{
Mutex mutex = null;
try
{
mutex = Mutex.OpenExisting("SINGLEINSTANCE");
if (mutex != null)
{
return;
}
}
catch (WaitHandleCannotBeOpenedException ex)
{
mutex = new Mutex(true, "SINGLEINSTANCE");
}
// critical section here
}
但是我知道正確的方法是這樣的:
private readonly Mutex m = new Mutex("SINGLEINSTANCE");
static void Main(string[] args) {
m.WaitOne();
try {
/* critical code */
}
finally {
m.ReleaseMutex();
}
}
這樣做是因為該應用程序只能同時運行一個進程。 它是一個控制台應用程序,為Web應用程序執行一些異步工作。
該代碼正在生產中,我不想更改它,除非此代碼有一些大問題...存在嗎?
舊代碼有一個競爭條件,其中兩個進程可以嘗試同時啟動,第二個啟動將引發異常並在new Mutex(true, "SINGLEINSTANCE");
上崩潰new Mutex(true, "SINGLEINSTANCE");
線。 如果互斥體已經存在,並且您沒有爭用條件,則程序將正常退出,並且從不執行關鍵部分。
您的新代碼無法編譯,因為您沒有為Mutex
使用有效的構造函數,但是,如果您傳入的是false
您的代碼將等待先前的互斥鎖被釋放,然后它將繼續執行關鍵部分,而不會退出程序早。
“正確”的方法是將兩種方法結合起來,嘗試創建互斥鎖,並使用重載與out
參數來查看您是否是互斥鎖的所有者。
static void Main(string[] args)
{
bool taken;
using(Mutex mutex = new Mutex(true, "SINGLEINSTANCE", out taken))
{
if(!taken)
return;
try
{
// critical section here
}
finally
{
mutex.ReleaseMutex();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.