C#— Timer实例何时被杀死?

如何解决C#— Timer实例何时被杀死?

| 给定以下代码,计时器将每秒触发一次PrintTimer函数,直到用户按下一个键。 问题1>计时器何时停止? 默认情况下,Timer是否为Background线程,以便在前台线程终止后将其杀死。 问题2>如何以编程方式在调用线程中停止计时器?
class Program
{
    // continue to call this function until the user presses a 
    // key to terminate the application
    static void PrintTime(object state) 
    {
        Console.WriteLine(\"Time is: {0}\",DateTime.Now.ToLongTimeString());
    }
    static void Main(string[] args)
    {
        TimerCallback timeCB = new TimerCallback(PrintTime);
        System.Threading.Timer t = new Timer(
            timeCB,null,1000);
        Console.WriteLine(\"Hit key to terminate...\");
        Console.ReadLine();
    }
}
    

解决方法

        答案1 现在,仅当程序退出时,计时器才会停止。它不是真的使用后台线程坐在那里,但是当发生计时器事件时,将通过作为后台线程的ThreadPool线程调用回调。 答案2 停止计时器很简单:
t.Change(Timeout.Infinite,Timeout.Infinite);
- 要么 -
t.Dispose();
前者允许您通过再次调用
Change
来重新启动
Timer
,而后者将完全清除
Timer
。 有关其行为的更多详细信息,建议阅读其MSDN文档中“ 3”类的“备注”部分。例如,使用
Dispose
会有一些棘手的时机,因为
Timer
可能已经将通知回调排队到线程池中,即使在调用
Dispose
之后,您在技术上也可以接收到该通知。     ,        计时器将通过其Finzalizer运行进行清理。那就是垃圾,实际上从发行版到调试模式都不同。 这是我们可以使用WeakReference运行的测试:
internal class Program
{
    // continue to call this function until the user presses a 
    // key to terminate the application
    private static void PrintTime(object state)
    {
        Console.WriteLine(\"Time is: {0}\",DateTime.Now.ToLongTimeString());
    }

    private static void Main(string[] args)
    {
        TimerCallback timeCB = new TimerCallback(PrintTime);
        Timer t = new Timer(
            timeCB,null,1000);

        WeakReference wk = new WeakReference(t);
        PrintStatus(wk);

        Console.WriteLine(\"Hit key to terminate...\");
        Console.ReadLine();

        t = null;
        PrintStatus(wk);
    }

    private static void PrintStatus(WeakReference wk)
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.WriteLine(\"Is timer alive? \" + wk.IsAlive);
    }
}
    ,        
Timer
是一次性的,因此您应该/必须在上面call7ѭ。如果要重用它,也可以调用
Stop
,但是Timer类中有一个带有定期回调的错误,建议您仅处置它并开始使用新的计时器。 在您发布的代码中将发生的事情是,将调用Timer的终结器(从技术上来说可能会杀死它)。     ,        在您的应用程序中,它永远不会停止,直到您退出应用程序。 要以编程方式停止它,取决于您使用的计时器。
System.Timers.Timer

System.Threading.Timer
如果是第一个,则可以调用Stop方法。 如果是第二个,则必须对其进行Dispose()。 请注意,如果您在某个方法中启动计时器,并且不保留对它的引用,则在收集垃圾时它将停止。     ,        对于问题2,请参见Timer.Enabled属性和Timer.Close()方法。 更新:我想为完整性起见,我还应该提到Timer.Stop()方法(将Enabled设置为false) 更新:什么时候应该使用每个选项? 广义上讲,有两种情况:要么您摆脱了计时器,不再计划再次使用它,要么暂停了计时器,但打算在某个时候恢复它(或者至少希望该选项能够使其恢复原状) )。 如果您不使用计时器,则可以采用“处置/关闭”的方法。至少您应该调用Dispose,因为这是一个表现良好的程序在完成一个实现IDisposable的对象时所希望执行的操作。 就是说,当对象同时实现IDisposable和Close方法时,我相信更好的方法是调用Close,因为Close可能做的不仅仅是释放资源。例如,它可能刷新缓冲区或执行某些其他对象特定的操作。人们会期望使用Close方法来调用Dispose。理想情况下,Close的文档应明确声明其调用Dispose(但Timer :: Close的文档并未说明确实如此)。 要临时暂停和恢复计时器,可以将Enabled属性设置为false,然后再次将其设置为true。或者,您可以调用Stop(),然后调用Start()以恢复它。临时而言,我不偏爱一种技术而不是另一种。 我想也许有人会认为Stop和Start的可读性和效率可能稍低(因为它们又将Enabled设置为)。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-