C# 测试记录
1、正常,同时开启两个线程
//启动函数 public void Test() { Thread thread1 = new Thread(() => SC1()); thread1.Start(); Thread thread2 = new Thread(() => SC2()); thread2.Start(); } public void SC1() { for (int i = 0; i < 50; i++) { Thread.Sleep(1000); Console.WriteLine("====我是SC1===="); } } public void SC2() { for (int i = 0; i < 50; i++) { Thread.Sleep(1000); Console.WriteLine("====我是SC2===="); } }
2、有序执行,无并发
//启动函数 public void Test() { Thread thread1 = new Thread(() => SC1()); thread1.Start(); Thread thread2 = new Thread(() => SC2()); thread2.Start(); } int sc1 = 0; int sc2 = 0; public void SC1() { if (Interlocked.Exchange(ref sc1, 1) == 0) { if (sc2 == 0) { for (int i = 0; i < 10; i++) { Thread.Sleep(500); Console.WriteLine("====我是SC1===="); } } } Interlocked.Exchange(ref sc1, 0); } public void SC2() { while (true) { if (sc1 == 0) { if (Interlocked.Exchange(ref sc2, 1) == 0) { for (int i = 0; i < 10; i++) { Thread.Sleep(500); Console.WriteLine("====我是SC2===="); } break; } } } Interlocked.Exchange(ref sc2, 0); }
3、模拟更新数据和上传时间
System.Timers.Timer getTimer = new System.Timers.Timer();
string getInterval = "1"; string uploadInterval = "1"; // 更新的时候不上传、上传的时候不更新 public AutoResetEvent ReplaceData = new AutoResetEvent(false);//更新 public AutoResetEvent UploadData = new AutoResetEvent(false);//上传 //是否开始更新、上传 public bool IsReplace = false; public bool IsUpload = false; public void DSQ() { //获取基本数据 getTimer.Elapsed += new ElapsedEventHandler(GetTimer_Elapsed); getTimer.Interval = int.Parse(getInterval) * 1000; getTimer.Start(); //上传校验数据 uploadTimer.Elapsed += new ElapsedEventHandler(UploadTimer_Elapsed); uploadTimer.Interval = int.Parse(uploadInterval) * 1000; uploadTimer.Start(); } //上传数据 private void UploadTimer_Elapsed(object sender, ElapsedEventArgs e) { IsUpload = true;//开始上传 if (IsReplace == true) { UploadData.WaitOne();//如果还在更新数据,则上传进行等待 } if (Interlocked.Exchange(ref inUploadTimer, 1) == 0) { for (int i = 0; i <5; i++) { Thread.Sleep(1000); Console.WriteLine($"=======第{i}次上传数据的========,{e.SignalTime}"); } Interlocked.Exchange(ref inUploadTimer, 0); IsUpload = false;//上传结束 ReplaceData.Set(); Console.WriteLine("上传数据完毕"); } } //获取并更新基本数据 private void GetTimer_Elapsed(object sender, ElapsedEventArgs e) { IsReplace = true;//开始更新 if (IsUpload == true) { ReplaceData.WaitOne();//如果在进行上传,则更新等待 } if (Interlocked.Exchange(ref inGetTimer, 1) == 0) { for (int i = 0; i < 5; i++) { Thread.Sleep(1000); Console.WriteLine($"=======第{i}次更新数据的========,{e.SignalTime}" ); } Interlocked.Exchange(ref inGetTimer, 0); IsReplace = false;//更新结束 UploadData.Set();//进行上传 Console.WriteLine("更新数据完毕"); } }
其他
作者:chenze 出处:https://www.cnblogs.com/chenze-Index/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 如果文中有什么错误,欢迎指出。以免更多的人被误导。 |