行业知识
C#-系统Timer会自动停止,使用线程进行连续性测试
2026-10-27 01:45:00
来源:互联网转载
文章速览
- 概述
- 代码结构
- 创建和执行
- 线程中执行的方法
- 停止线程
- 参考文章
坚持记录实属不易,希望友善多金的码友能够随手点一个赞。
()共同创建氛围更加良好的开发者社区!
谢谢~
()概述
接上片Timer计时器的文章:C#中System.Threading.Timer的使用。
利用周末时间测试了一下System.Threading.Timer的性能,发现两个问题:
1、会出现一些内存泄露的问题,第一天晚上出现了Out of memory的异常,由于是深夜没有第一时间看到线程,早上发现的时候已经中止了,所以还无法完全断定是因为Timer的原因,但后续测试了一下,在跑几个小时后,timer还是会容易出现一些内存泄露的问题,当然我是在里面进行了一些逻辑处理、页面UI的展示和硬件设备的调用;
2、长时间运行后,还是会出现自动停止的现象
故此使用线程进行连续性测试。
代码结构
创建和执行
//全局变量 Thread Looper; private void btnFatigueTest_Click(object sender, EventArgs e) { GroupControl(false); btn_FatigueCap.Enabled = false; btn_StopCap.Enabled = true; //硬件执行方法调用//创建线程 Looper = new Thread(new ThreadStart(Loop)); //执行线程 Looper.Start(); }线程中执行的方法
int count = 1; int count2 = 1; bool IsPointB; /// /// 循环调用方法 /// /// private void Loop() { while (true) { //线程睡眠1000ms Thread.Sleep(CameraHost.TimeOut); string name = IsPointB ? "B" : "A"; IsPointB = !IsPointB; //获取硬件结果 var filepath = .... if (File.Exists(filepath)) { BeginInvoke(new Action(() => { lb_Count.Text = "次数" + count++; })); } else { MainDeviceProvider.Instance.Logger.Warning($"出错 :{count2++}/{count - 1}"); } //主动GC,系统不一定听你的 tin GC.Collect(); } }停止线程
private void btn_StopCap_Click(object sender, EventArgs e) { //终止线程 Looper.Abort(); GroupControl(true); count = 1; btn_FatigueCap.Enabled = true; btn_StopCap.Enabled = false; }参考文章
C#多线程——Thread睡眠、中断、合并、暂停与恢复、终止