單一實例應用程式指的是在你的作業系統中你只能開一個的程式
例如說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.
}
}
}
}