アプリケーションの複数インスタンスの防止に関する記事で、Michael Covington は次のコードを提示しています。
static void Main() // args are OK here, of course
{
bool ok;
m = new System.Threading.Mutex(true, "YourNameHere", out ok);
if (! ok)
{
MessageBox.Show("Another instance is already running.");
return;
}
Application.Run(new Form1()); // or whatever was there
GC.KeepAlive(m); // important!
}
彼は、GC.KeepAlive(m) は、ミューテックスへの追加の参照がないため、ガベージ コレクターがミューテックスを早期に収集するのを防ぐために必要であると説明しています。
私の質問: ミューテックスを using でラップすると、同じことができますか? つまり、次のことも GC が私の下から敷物を引き出すのを防ぐのでしょうか?
static void Main() // args are OK here, of course
{
bool ok;
using (var m = new System.Threading.Mutex(true, "YourNameHere", out ok))
{
if (! ok)
{
MessageBox.Show("Another instance is already running.");
return;
}
Application.Run(new Form1()); // or whatever was there
}
}
私の直感的な反応は、 using は次と同等である(と思われる)ため、 using が機能するということです。
Mutex m = new System.Threading.Mutex(true, "YourNameHere", out ok);
try
{
// do stuff here
}
finally
{
m.Close();
}
そして、 m.Close() があれば、別の参照があることを JIT コンパイラに通知するのに十分であり、時期尚早のガベージ コレクションを防ぐことができると思います。