CLR via C# 读书笔记 3-1 一种单实例应用程序的实现(信号量)

单实例应用程序指的是在你的操作系统中你只能开一个的程序

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

 

转载于:https://www.cnblogs.com/PurpleTide/archive/2010/11/18/1880718.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值