• 给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完美解决。

  • 相关阅读:
    非常精辟的几句话
    关于免杀的实践
    分析PE
    分析 Nanocore
    CTO的窘境
    企业级容器云平台
    POJ 2274
    POJ 1703
    POJ 1182
    DNS协议以及报文格式总结
  • 原文地址:https://www.cnblogs.com/mq0036/p/4138447.html
Copyright © 2020-2023  润新知