C# -- 多线程向同一文件写入
生活随笔
收集整理的這篇文章主要介紹了
C# -- 多线程向同一文件写入
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. 多線程向同一文件寫入Log.
public delegate void AsyncLog(string str1, string str2);private void Test() {Console.WriteLine("Test Start...");for (int i = 0; i < 100; i++){AsyncLog asyLog1 = new AsyncLog(WriteLog);asyLog1.BeginInvoke("EventActionA" + i.ToString(), "EventContentA" + i.ToString(), null, null);AsyncLog asyLog2 = new AsyncLog(WriteLog);asyLog2.BeginInvoke("EventActionB" + i.ToString(), "EventContentB" + i.ToString(), null, null);AsyncLog asyLog3 = new AsyncLog(WriteLog);asyLog3.BeginInvoke("EventActionC" + i.ToString(), "EventContentC" + i.ToString(), null, null);}Console.WriteLine("Test End..."); } public static object lockObject = new object();
private void WriteLog(string strEventType, string strEventContent) {lock (lockObject){Console.WriteLine("Write Log start... ThreadID:{0}", Thread.CurrentThread.ManagedThreadId);string strLogPath = string.Format("D:\\Log\\Log{0}.log", DateTime.Now.ToString("yyyy-MM-dd"));if (!File.Exists(strLogPath)){File.Create(strLogPath).Close();}FileStream fs = new FileStream(strLogPath, FileMode.Append, FileAccess.Write);StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);sw.WriteLine(string.Format("{0} {1}", strEventType, strEventContent));sw.Close();fs.Close();Console.WriteLine("Write Log End ThreadID:{0}", Thread.CurrentThread.ManagedThreadId);} }
?
轉(zhuǎn)載于:https://www.cnblogs.com/ChengWenHao/p/MultiThreadWriteFile.html
總結(jié)
以上是生活随笔為你收集整理的C# -- 多线程向同一文件写入的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VMware配置linux网络步骤
- 下一篇: C# 设计模式,工厂方法