0


C#-系统Timer会自动停止,使用线程进行连续性测试

文章速览

坚持记录实属不易,希望友善多金的码友能够随手点一个赞。
共同创建氛围更加良好的开发者社区!
谢谢~

概述

接上片Timer计时器的文章:C#中System.Threading.Timer的使用。
利用周末时间测试了一下System.Threading.Timer的性能,发现两个问题:
1、会出现一些内存泄露的问题,第一天晚上出现了Out of memory的异常,由于是深夜没有第一时间看到线程,早上发现的时候已经中止了,所以还无法完全断定是因为Timer的原因,但后续测试了一下,在跑几个小时后,timer还是会容易出现一些内存泄露的问题,当然我是在里面进行了一些逻辑处理、页面UI的展示和硬件设备的调用;
2、长时间运行后,还是会出现自动停止的现象
故此使用线程进行连续性测试。

代码结构

创建和执行

//全局变量Thread Looper;privatevoidbtnFatigueTest_Click(object sender,EventArgs e){GroupControl(false);
            btn_FatigueCap.Enabled =false;
            btn_StopCap.Enabled =true;//硬件执行方法调用//创建线程
            Looper =newThread(newThreadStart(Loop));//执行线程
            Looper.Start();}

线程中执行的方法

int count =1;int count2 =1;bool IsPointB;/// <summary>/// 循环调用方法/// </summary>/// <param name="sender"></param>privatevoidLoop(){while(true){//线程睡眠1000ms
                Thread.Sleep(CameraHost.TimeOut);string name = IsPointB ?"B":"A";
                IsPointB =!IsPointB;//获取硬件结果var filepath =....if(File.Exists(filepath)){BeginInvoke(newAction(()=>{
                        lb_Count.Text ="次数"+ count++;}));}else{
                    MainDeviceProvider.Instance.Logger.Warning($"出错 :{count2++}/{count -1}");}//主动GC,系统不一定听你的tin               GC.Collect();}}

停止线程

privatevoidbtn_StopCap_Click(object sender,EventArgs e){//终止线程
            Looper.Abort();GroupControl(true);
            count =1;
            btn_FatigueCap.Enabled =true;
            btn_StopCap.Enabled =false;}

参考文章

C#多线程——Thread睡眠、中断、合并、暂停与恢复、终止

标签: c# 开发语言

本文转载自: https://blog.csdn.net/qq_43733614/article/details/139226166
版权归原作者 默九思 所有, 如有侵权,请联系我们删除。

“C#-系统Timer会自动停止,使用线程进行连续性测试”的评论:

还没有评论