背景:
最近在作一個項目,程序是命令行程序,在主程序中開一個線程,這個線程用到了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完美解決。併發