支持多线程写入txt,日志文件
第一种文件共享方式会丢失数据,FileShare.Write:
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); }
第二种 ReaderWriterLockSlim:
public static void WriteFile(string i) { var sqlPath= System.IO.Directory.GetCurrentDirectory()+ "\\log\\sql"; if (!Directory.Exists(sqlPath)) { DirectoryInfo di = Directory.CreateDirectory(sqlPath); } var logFilePath = sqlPath + "\\"+DateTime.Now.ToString("yyyy-MM-dd")+".txt"; lockSlim.EnterWriteLock();//打开写操作锁 try { string TestText = i.ToString(); File.AppendAllText(logFilePath, i+ "\r\n"); } finally { lockSlim.ExitWriteLock();//占用完后退出 } }
推荐第二种
完整版:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace StdioMQTT { public class LogHelper { static ReaderWriterLockSlim lockSlim = new ReaderWriterLockSlim(); public static void SqlWriteFile(string i) { var sqlPath = System.IO.Directory.GetCurrentDirectory() + "\\log\\sql"; if (!Directory.Exists(sqlPath)) { DirectoryInfo di = Directory.CreateDirectory(sqlPath); } var logFilePath = sqlPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; lockSlim.EnterWriteLock();//打开写操作锁 try { string TestText = i+ DateTime.Now.ToString(); File.AppendAllText(logFilePath, i + "\r\n"); } finally { lockSlim.ExitWriteLock();//占用完后退出 } } public static void InfoWriteFile(string i) { var sqlPath = System.IO.Directory.GetCurrentDirectory() + "\\log\\info"; if (!Directory.Exists(sqlPath)) { DirectoryInfo di = Directory.CreateDirectory(sqlPath); } var logFilePath = sqlPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; lockSlim.EnterWriteLock();//打开写操作锁 try { string TestText = i+DateTime.Now.ToString(); File.AppendAllText(logFilePath, i + "\r\n"); } finally { lockSlim.ExitWriteLock();//占用完后退出 } } public static void ErroWriteFile(string i) { var sqlPath = System.IO.Directory.GetCurrentDirectory() + "\\log\\erro"; if (!Directory.Exists(sqlPath)) { DirectoryInfo di = Directory.CreateDirectory(sqlPath); } var logFilePath = sqlPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; lockSlim.EnterWriteLock();//打开写操作锁 try { string TestText = i + DateTime.Now.ToString(); File.AppendAllText(logFilePath, i + "\r\n"); } finally { lockSlim.ExitWriteLock();//占用完后退出 } } } }