CLR via C# 讀書筆記 3-1 一種單一實例應用程式的實現(訊號量)

來源:互聯網
上載者:User

單一實例應用程式指的是在你的作業系統中你只能開一個的程式

例如說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.
}
}
}
}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.