C#一种简单而有效的进程间同步

1using System; 2using System.Threading; 3using System.Threading.Tasks; 4namespace InterProcessSynchronization 5{ 6 class InterProcessSync 7 { 8 static void Main(string[] args) 9 { 10 string MutexName = "InterProcessSyncName"; 11 Mutex SyncNamed; //声明一个已命名的互斥对象 12 try 13 { 14 SyncNamed = Mutex.OpenExisting(MutexName); //如果此命名互斥对象已存在则请求打开 15 } 16 catch (WaitHandleCannotBeOpenedException) 17 { 18 SyncNamed = new Mutex(false, MutexName); //如果初次运行没有已命名的互斥对象则创建一个 19 } 20 Task MulTesk = new Task 21 ( 22 () => //多任务并行计算中的匿名方法,用委托也可以 23 { 24 for (; ; ) //为了效果明显而设计 25 { 26 Console.WriteLine("当前进程等待获取互斥访问权......"); 27 SyncNamed.WaitOne(); 28 Console.WriteLine("获取互斥访问权,访问资源完毕,按回车释放互斥资料访问权."); 29 Console.ReadLine(); 30 SyncNamed.ReleaseMutex(); 31 Console.WriteLine("已释放互斥访问权。"); 32 } 33 } 34 ); 35 MulTesk.Start(); 36 MulTesk.Wait(); 37 } 38 } 39}

以上程序编译后,请运行两个实例即两个进程。就可以明显的看出进程间的同步的实现。

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

GitHub 上有哪些适合新手跟进的优质项目?

!(https://oscimg.oschina.net/oscnet/011f28e3bc332010e1442e6c00ed344805d.jpg)点击上方“迈微电子研发社”,选择“星标★”公众号重磅干货,第一时间送达!(https://oscimg.oschina.net/oscnet/cd44ba75f

C# CRC16 modbus

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceWaterBubbleCheck{

C# 一个数组集合,任意组合,不遗漏,不重复

usingSystem;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;names

Mvc+三层(批量添加、删除、修改)

DAL层usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingModel;usingSystem.Data;usingNe