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