zoukankan      html  css  js  c++  java
  • 给System.Timer类的Elapsed事件加锁

    背景:
    最近在做一个项目,程序是命令行程序,在主程序中开一个线程,这个线程用到了System.Timer类的Elapsed事件,根据指定时间间隔循环去查询数据库,找符合条件的记录,把记录组织成xml对象发送到MSMQ中去。刚一开始的时候数据量小,在时间间隔内可以查询所有的记录并发送到MSMQ,随着业务量大增大,在时间间隔内会多次执行查询数据库发送MSMQ,这样就会产生重复的数据发送到MSMQ了。所以本次在System.Timer类的Elapsed事件中加锁,使上次任务执行完之前,后面的任务无法执行。

    程序代码:

        public class ThreadSendMQ
        {
            public void Work(object th)
            {
                string str = "消息队列发送模式:多线程发送模式。";
                Console.WriteLine(str);
    
                System.Timers.Timer t = new System.Timers.Timer();
                t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
                t.Interval = 1000 * Convert.ToInt16(ConfigManager.SleepTime);
                t.Enabled = true;
            }
    
            void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                //加锁检查数据库和发送MSMQ
                lock (this)
                {
                    send();
                }
            }
    
            private void send()
            {
                string str = "线程正在发送消息队列";
                //线程查询数据库并发送到MSMQ中去。
                //Console.Write(str);
                //LogManager.WriteFilerLog(ConfigManager.LogPath, str);
            }
        }
    
    ///////   主程序  //////////////
        class Program
        {
            static void Main(string[] args)
            {
                ThreadSendMQ thSend = new ThreadSendMQ();
                System.Threading.ParameterizedThreadStart thrParm = new System.Threading.ParameterizedThreadStart(thSend.Work);
                System.Threading.Thread thread = new System.Threading.Thread(thrParm);
                thread.Start(System.Threading.Thread.CurrentThread);
            }
        }

     经过上面的锁,就可以防止任务的多次执行,当前项目的bug完美解决。

  • 相关阅读:
    HTML中CSS入门基础
    HTML基本代码教学,第三天
    HTML基本代码教学,第二天
    HTML基本代码教学片,认识HTML
    开学第一天,规章制度,教学大纲
    新的学期,从头开始
    开启新模式WinForm
    封装、继承、多态的基本详细使用方式与方法以及含义
    Python开发基础-Day4-布尔运算、集合
    Python开发基础-Day3-列表、元组和字典
  • 原文地址:https://www.cnblogs.com/mq0036/p/4138447.html
Copyright © 2011-2022 走看看