支持多線程寫入txt,日誌文件

 static void WriteLog()
        {
            try
            {
                var logFilePath = "log.txt";
                var now = DateTime.Now;
                var logContent = string.Format("Tid: {0}{1} {2}.{3}\r\n", Thread.CurrentThread.ManagedThreadId.ToString().PadRight(4), now.ToLongDateString(), now.ToLongTimeString(), now.Millisecond.ToString());

                var logContentBytes = Encoding.Default.GetBytes(logContent);
                //由於設置了文件共享模式爲允許隨後寫入,所以即使多個線程同時寫入文件,也會等待之前的線程寫入結束之後再執行,而不會出現錯誤
                using (FileStream logFile = new FileStream(logFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                {
                    logFile.Seek(0, SeekOrigin.End);
                    logFile.Write(logContentBytes, 0, logContentBytes.Length);
                }

                 
            }
            catch (Exception ex)
            {
                 
                Console.WriteLine(ex.Message);
            }

  

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