C#實現(xiàn)多線程寫入同一個文件的方法
更新時間:2015年08月22日 10:29:36 作者:我心依舊
這篇文章主要介紹了C#實現(xiàn)多線程寫入同一個文件的方法,涉及C#多線程操作文件讀寫的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#實現(xiàn)多線程寫入同一個文件的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
namespace WfpApp { public partial class Form2 : Form { object obj = new object(); public Form2() { InitializeComponent(); System.Threading.Thread thread; string[] users = new string[] { "zkk", "admin", "administrator", "soft", "iany", "nec", "necsl" }; for (int i = 0; i < users.Length; i++) { thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(WriteLock)); thread.Start(users[i]); } } public void WriteThread(object user) { string path = System.Windows.Forms.Application.StartupPath + "\\app\\"; if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); path = path + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt"; StringBuilder sb = new StringBuilder(); sb.AppendLine("----------------------------" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "--------------------------"); sb.AppendLine(user.ToString()); sb.AppendLine("---------------------------------------------------------------------------------"); sb.AppendLine(); //if (!System.IO.File.Exists(path)) // System.IO.File.Create(path).Close(); System.IO.FileStream fileStream = new System.IO.FileStream(path, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite); System.IO.StreamWriter sw = new System.IO.StreamWriter(fileStream, Encoding.Default); sw.Write(sb.ToString()); sw.Close(); sw.Dispose(); fileStream.Close(); fileStream.Dispose(); } public void WriteLock(object user) { lock (obj) { string path = System.Windows.Forms.Application.StartupPath + "\\app\\"; if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); path = path + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt"; StringBuilder sb = new StringBuilder(); sb.AppendLine("----------------------------" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "--------------------------"); sb.AppendLine(user.ToString()); sb.AppendLine("---------------------------------------------------------------------------------"); sb.AppendLine(); if (!System.IO.File.Exists(path)) System.IO.File.Create(path).Close(); System.IO.FileStream fileStream = new System.IO.FileStream(path, System.IO.FileMode.Append, System.IO.FileAccess.Write); System.IO.StreamWriter sw = new System.IO.StreamWriter(fileStream, Encoding.Default); sw.Write(sb.ToString()); sw.Close(); sw.Dispose(); fileStream.Close(); fileStream.Dispose(); } } } }
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
C#緩存之SqlCacheDependency用法實例總結(jié)
這篇文章主要介紹了C#緩存之SqlCacheDependency用法,在C#程序設(shè)計中有一定的實用價值,需要的朋友可以參考下2014-08-08Winform中GridView分組排序功能實現(xiàn)方法
這篇文章主要介紹了Winform中GridView分組排序功能實現(xiàn)方法,以實例形式詳細(xì)說明了分組排序的實現(xiàn)方法,并附帶完整的DBHelp類代碼,是非常實用的技巧,需要的朋友可以參考下2014-11-11C# 9 新特性——record的相關(guān)總結(jié)
這篇文章主要介紹了C# 9 新特性——record的相關(guān)總結(jié),幫助大家更好的理解和學(xué)習(xí)使用c# 9的新特性,感興趣的朋友可以了解下2021-02-02