单实例应用程序指的是在你的操作系统中你只能开一个的程序
例如说outlook
以下代码通过 Semaphore 实行了一个单实例的控制
(事实上你使用EventWaitHandle 或者 Mutex都是可以的)
原理是因为windows不允许重名的核心对象 ,例子中是 "SomeUniqueStringIdentifyingMyApp"
第一次调用Semaphore的时候,系统将创建一个对象并将createdNew设置为true
第二次调用Semaphore的时候,系统返回现有同名对象并将createdNew设置为false
using
System;
using System.Threading;
public static class Program
{
public static void Main()
{
Boolean createdNew;
// Try to create a kernel object with the specified name
using ( new Semaphore( 0 , 1 , " SomeUniqueStringIdentifyingMyApp " , out createdNew))
{
if (createdNew)
{
// This thread created the kernel object so no other instance of this
// application must be running. Run the rest of the application here...
}
else
{
// This thread opened an existing kernel object with the same string name;
// another instance of this application must be running now.
// There is nothing to do in here, let's just return from Main to terminate
// this second instance of the application.
}
}
}
}
using System.Threading;
public static class Program
{
public static void Main()
{
Boolean createdNew;
// Try to create a kernel object with the specified name
using ( new Semaphore( 0 , 1 , " SomeUniqueStringIdentifyingMyApp " , out createdNew))
{
if (createdNew)
{
// This thread created the kernel object so no other instance of this
// application must be running. Run the rest of the application here...
}
else
{
// This thread opened an existing kernel object with the same string name;
// another instance of this application must be running now.
// There is nothing to do in here, let's just return from Main to terminate
// this second instance of the application.
}
}
}
}