在他关于防止应用程序的多个实例的文章中,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!
}
Run Code Online (Sandbox Code Playgroud)
他解释说,GC.KeepAlive(m)是防止垃圾收集器尽早收集互斥锁所必需的,因为没有额外的引用.
我的问题:将mutex包装在一个使用中做同样的事情?也就是说,以下是否也会阻止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 …Run Code Online (Sandbox Code Playgroud)