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