C#实现多线程写入同一个文件的方法

2019-12-26 13:15:04于丽

易采站长站为您分析C#实现多线程写入同一个文件的方法,涉及C#多线程操作文件读写的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了C#实现多线程写入同一个文件的方法。。具体实现方法如下:

 

  1. namespace WfpApp  { 
  2. public partial class Form2 : Form  { 
  3. object obj = new object();  public Form2() 
  4. {  InitializeComponent(); 
  5. System.Threading.Thread thread;  string[] users = new string[] { "zkk", "admin", "administrator", "soft", "iany", "nec", "necsl" }; 
  6. for (int i = 0; i < users.Length; i++)  { 
  7. thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(WriteLock));  thread.Start(users[i]); 
  8. }  } 
  9. public void WriteThread(object user)  { 
  10. string path = System.Windows.Forms.Application.StartupPath + "app";  if (!System.IO.Directory.Exists(path)) 
  11. System.IO.Directory.CreateDirectory(path);  path = path + "" + DateTime.Now.ToString("yyyyMMdd") + ".txt"; 
  12. StringBuilder sb = new StringBuilder();  sb.AppendLine("----------------------------" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "--------------------------"); 
  13. sb.AppendLine(user.ToString());  sb.AppendLine("---------------------------------------------------------------------------------"); 
  14. sb.AppendLine();  //if (!System.IO.File.Exists(path)) 
  15. // 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); 
  16. System.IO.StreamWriter sw = new System.IO.StreamWriter(fileStream, Encoding.Default);  sw.Write(sb.ToString()); 
  17. sw.Close();  sw.Dispose(); 
  18. fileStream.Close();  fileStream.Dispose(); 
  19. }  public void WriteLock(object user)