首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >timer_Elapsed()事件不触发

timer_Elapsed()事件不触发
EN

Stack Overflow用户
提问于 2016-06-09 11:00:38
回答 2查看 1K关注 0票数 0

我使用的计时器在Windows上的OnStart()方法处理timer_Elapsed()事件检查后,每5分钟。

但是timer_Elapsed()在5分钟后没有开火/呼叫,如果我在下面的代码中做错了什么,请纠正我。

代码语言:javascript
复制
        protected override void OnStart(string[] args)
        {
            try
            {
                genLogs.WriteErrorLog("Service Started OnStart.");
                //int tmStart = Convert.ToInt32(ConfigurationManager.AppSettings["tim"]);
                using (Timer timer = new Timer(30000))  //  (1000 * 5 * 60) for 5 minutes
                {
                    timer.Elapsed += timer_Elapsed;
                    timer.Start();
                    //Console.WriteLine("Timer is started");
                    genLogs.WriteErrorLog("Timer is started.");
                    //Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                genLogs.WriteErrorLog("OnStart Service Error: " + ex.Message);
            }

        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                genLogs.WriteErrorLog("Service Started Checking Windows Services and Web AppPools.");

                serviceLogic.InsertStatus();

                genLogs.WriteErrorLog("Service Calls Send SendEmails Method.");
                serviceLogic.SendInfo();
            }
            catch (Exception ex)
            {
                genLogs.WriteErrorLog("OnStart Service Error: " + ex.Message);
            }
        }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-06-09 11:10:12

我想这可能是因为你是在用的块里做的。

代码语言:javascript
复制
using (Timer timer = new Timer(30000))  //  (1000 * 5 * 60) for 5 minutes
            {
                timer.Elapsed += timer_Elapsed;
                timer.Start();
                //Console.WriteLine("Timer is started");
                genLogs.WriteErrorLog("Timer is started.");
                //Console.ReadLine();
            } <- Your timer stops existing here

在using块中执行此操作与使用timer.Dispose()相同,后者处理计时器,因此不能调用任何方法。这应该是可行的:

代码语言:javascript
复制
Timer timer = new Timer(30000)
timer.Elapsed += timer_Elapsed;
timer.Start();
票数 3
EN

Stack Overflow用户

发布于 2016-06-09 11:13:20

配置计时器使得无法运行回调。

如果您希望将其释放,则必须同步该调用。

查看这篇文章-> How do I gracefully stop a System.Threading.Timer?

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37724094

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档