• 多线程程序写日志时遇到加锁的问题


       前段时间在做项目时,系统是个多线程程序,几个线程都需要写日志,主线程和通讯线程经常在写日志时打架,为了解决这个问题,考虑在写日志的方法中加锁。代码如下:

         /// <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;
            }

    经过加锁处理后,多线程写日志打架的问题得到了解决。

  • 相关阅读:
    Equivalent Sets HDU
    Chemical table CFR500 div2D(并查集)
    How do I create an installation log?
    Error 1937.An error occurred during the installation of assembly...
    InstallShield 版本转换
    Convert CString to TCHAR
    InstallShield : 如何查找编译后的 Merge Module存放路径
    Msi.h causes compilation error in vs2010
    区间调度(贪心)
    硬币问题(贪心)
  • 原文地址:https://www.cnblogs.com/kevinGao/p/2181380.html
Copyright © 2020-2023  润新知