CLR via C# 讀書筆記 3-1 一種單實(shí)例應(yīng)用程序的實(shí)現(xiàn)(信號量)
單實(shí)例應(yīng)用程序指的是在你的操作系統(tǒng)中你只能開一個(gè)的程序
例如說outlook
以下代碼通過 Semaphore 實(shí)行了一個(gè)單實(shí)例的控制
(事實(shí)上你使用EventWaitHandle 或者 Mutex都是可以的)
原理是因?yàn)閣indows不允許重名的核心對象 ,例子中是 "SomeUniqueStringIdentifyingMyApp"
第一次調(diào)用Semaphore的時(shí)候,系統(tǒng)將創(chuàng)建一個(gè)對象并將createdNew設(shè)置為true
第二次調(diào)用Semaphore的時(shí)候,系統(tǒng)返回現(xiàn)有同名對象并將createdNew設(shè)置為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.
}
}
}
}
浙公網(wǎng)安備 33010602011771號