C# lock示例
这两天项目加了个需求,需要给PLC发心跳信号
我又不想在原来的循环中加,所以想着再弄个timer来定时发信号。
只是这样会有一个问题,就是冲突。
两个线程之间,有可能同时与plc发生通讯,引起数据混乱。
private void button1_Click(object sender, EventArgs e) { Thread t1 = new Thread(() => { for(int i = 0; i < 1000; i++) { runTask1("线程1"); } }); t1.Start(); Thread t2 = new Thread(() => { for (int i = 0; i < 1000; i++) { runTask2("线程2"); } }); t2.Start(); } public static readonly object lockObj = new object(); public int mNum = 0; public void runTask1(string msg) { //Thread t1 = new Thread(()=> { //}); lock (lockObj) { Console.WriteLine("任务1执行。。。" + mNum.ToString() + "," + msg); Thread.Sleep(10); Console.WriteLine("任务1结束。。。" + mNum.ToString() + "," + msg); Thread.Sleep(10); mNum++; } } //public int mNum = 0; public void runTask2(string msg) { //Thread t1 = new Thread(()=> { //}); lock (lockObj) { Console.WriteLine("任务2执行。" + mNum.ToString() + "," + msg); Thread.Sleep(5); Console.WriteLine("任务2结束。" + mNum.ToString() + "," + msg); Thread.Sleep(8); mNum++; } } public void runTask3(string msg) { //Thread t1 = new Thread(()=> { //}); lock (lockObj) { Console.WriteLine("任务3执行。****" + mNum.ToString() + "," + msg); Thread.Sleep(5); Console.WriteLine("任务3结束。****" + mNum.ToString() + "," + msg); Thread.Sleep(8); mNum++; } } private void button2_Click(object sender, EventArgs e) { if (timer1.Enabled) { timer1.Stop(); } else { timer1.Start(); } } private void timer1_Tick(object sender, EventArgs e) { runTask3("时钟任务。"); }
所以就 要使用lock
在某个线程和PLC通讯时,另一个线程不能使用。