c# mutex使用示例
2013-02-04 16:44
120 查看
来自:http://outofmemory.cn/code-snippet/1631/c-mutex-usage-example
Mutex:/mjuteks/互斥(体) 又称同步基元使用了System.Threading 命名空间。
当创建一个应用程序类时,将同时创建一个系统范围内的命名的Mutex对象。这个互斥元在整个操作系统中都是可见的。当已经存在一个同名的互斥元时,构造函数将会输出一个布尔值。程序代码通过检测这个布尔值来判断指定的程序实例是否启动,如果已经存在同名互斥元的话,则显示一个对话框,告知用户应用程序已经启动,并退出应用程序
Mutex:/mjuteks/互斥(体) 又称同步基元使用了System.Threading 命名空间。
当创建一个应用程序类时,将同时创建一个系统范围内的命名的Mutex对象。这个互斥元在整个操作系统中都是可见的。当已经存在一个同名的互斥元时,构造函数将会输出一个布尔值。程序代码通过检测这个布尔值来判断指定的程序实例是否启动,如果已经存在同名互斥元的话,则显示一个对话框,告知用户应用程序已经启动,并退出应用程序
using System.Runtime.InteropServices; //GuidAttribute using System.Reflection; //Assembly using System.Threading; //Mutex using System.Security.AccessControl; //MutexAccessRule using System.Security.Principal; //SecuirtyIdentifier static void Main(string[] args) { // get application GUID as defined in AssemblyInfo.cs string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); // unique id for global mutex - Global prefix means it is global to the machine string mutexId = string.Format( "Global\\{{{0}}}", appGuid ); using (var mutex = new Mutex(false, mutexId)) { // edited by Jeremy Wiebe to add example of setting up security for multi-user usage // edited by 'Marc' to work also on localized systems (don't use just "Everyone") var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); // edited by acidzombie24 var hasHandle = false; try { try { // note, you may want to time out here instead of waiting forever // edited by acidzombie24 // mutex.WaitOne(Timeout.Infinite, false); hasHandle = mutex.WaitOne(5000, false); if (hasHandle == false) throw new TimeoutException("Timeout waiting for exclusive access"); } catch (AbandonedMutexException) { // Log the fact the mutex was abandoned in another process, it will still get aquired hasHandle = true; } // Perform your work here. } finally { // edited by acidzombie24, added if statemnet if(hasHandle) mutex.ReleaseMutex(); } } }
相关文章推荐
- 云服务器 ECS Linux 下使用 NTFS 文件系统示例
- Control Study->AdRotator广告控件显示自定义配置文件中广告以及与DataGrid控件结合使用显示图片(示例代码下载)
- Python使用回溯法子集树模板解决爬楼梯问题示例
- Java嵌入式数据库LMini-0.1.2及其通讯录使用示例发布
- C语言--static全局使用示例
- 使用JSTL中的c:out标签显示String类型变量的示例
- 使用 ActiveMQ 示例
- Python(2.7.x)使用SMTP发送邮件的简单示例
- 电路与Multisim 变压器的使用示例
- php示例代码之 使用PHP的MySQL标准函数
- 在项目中简单使用枚举的示例代码
- jquery ready函数、css函数及text()使用示例
- Kryo框架使用方法代码示例
- 使用C#设置IIS站点运行的.Net版本示例
- C#使用LitJson解析JSON的示例代码
- Mono.Cecil使用示例之获取源文件路径
- C++11中union的使用方法示例
- flashbuilder使用竖条图表ColumnChart示例
- snooper taoism 2中的sm3使用示例
- prepareStatement使用示例