Mutex通过设置mutexName实现会话状态下单实例运行
mutexName= "Local\\" +"AppName";
只对创建它的会话有效,也就是说新开启一个远程链接时会再次启动 ConsoleApp实例。
private static void LocalMutex()
{
// 是否第一次创建mutex
bool newMutexCreated = false;
string mutexName = "Local\\" + "tenghoo";
Mutex mutex = null;
try
{
mutex = new Mutex(false, mutexName, out newMutexCreated);
}
catch (Exception ex)
{
Console.Write(ex.Message);
System.Threading.Thread.Sleep(3000);
Environment.Exit(1);
}
// 第一次创建mutex
if (newMutexCreated)
{
Console.WriteLine("程序已启动");
//todo:此处为要执行的任务
}
else
{
Console.Write("另一个窗口已在运行,3秒以后自动关闭。。");
System.Threading.Thread.Sleep(1000);
Console.Write("1");
System.Threading.Thread.Sleep(1000);
Console.Write("2");
System.Threading.Thread.Sleep(1000);
Console.Write("3");
Environment.Exit(1);//退出程序
}
}
{
// 是否第一次创建mutex
bool newMutexCreated = false;
string mutexName = "Local\\" + "tenghoo";
Mutex mutex = null;
try
{
mutex = new Mutex(false, mutexName, out newMutexCreated);
}
catch (Exception ex)
{
Console.Write(ex.Message);
System.Threading.Thread.Sleep(3000);
Environment.Exit(1);
}
// 第一次创建mutex
if (newMutexCreated)
{
Console.WriteLine("程序已启动");
//todo:此处为要执行的任务
}
else
{
Console.Write("另一个窗口已在运行,3秒以后自动关闭。。");
System.Threading.Thread.Sleep(1000);
Console.Write("1");
System.Threading.Thread.Sleep(1000);
Console.Write("2");
System.Threading.Thread.Sleep(1000);
Console.Write("3");
Environment.Exit(1);//退出程序
}
}