多線程程序寫日誌時遇到加鎖的問題

   前段時間在做項目時,系統是個多線程程序,幾個線程都需要寫日誌,主線程和通訊線程經常在寫日誌時打架,爲了解決這個問題,考慮在寫日誌的方法中加鎖。代碼如下:

     /// <summary>
        /// 寫日誌時加鎖
        /// </summary>
        private static object m_Lock = new object();

 

        /// <summary>
        /// 寫日誌文件的接口函數,此函數只向指定的文件寫入字符串

        /// </summary>
        /// <param name="DestFileName"></param>
        /// <param name="fmt"></param>
        /// <returns></returns>
        public static int TP_WriteAppLogFileEx(string DestFileName, string fmt)
        {
            string strLogFile = System.Environment.CurrentDirectory+"\\Log\\"+DateTime.Now.ToString("yyyyMMdd")+".log";
            if (strLogFile != DestFileName)
            {
                DestFileName = strLogFile;
            }
            int iWriteAppLogFile = 0;
            lock (m_Lock)
            {
                iWriteAppLogFile=TP_WriteAppLogFile(DestFileName, fmt);
            }
            return iWriteAppLogFile;
        }

 

 public static int TP_WriteAppLogFile(string DestFileName, string fmt)
        {
            try
            {
   FileInfo file = new FileInfo(DestFileName);

                if (!file.Exists)
                {
                    file.Create();
                }

                //定位到文件尾
                StreamWriter stream = file.AppendText();

                //寫當前的時間
                stream.Write(DateTime.Now.ToString("HH:mm:ss fff "));

                //寫用戶傳過來的字符串
                stream.WriteLine(fmt);

                //最後記着要關了它
                stream.Close(); 


            }
            catch (Exception e)
            {

            }

            return 0;
        }

經過加鎖處理後,多線程寫日誌打架的問題得到了解決。

 

轉載於:https://www.cnblogs.com/kevinGao/archive/2011/09/19/2181380.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章