SoFunction
Updated on 2025-03-07

C# implements the method of writing the same file by multiple threads

This article describes the method of C# to write multiple threads to the same file. Share it for your reference. The specific implementation method is as follows:

namespace WfpApp
{
 public partial class Form2 : Form
 {
  object obj = new object();
  public Form2()
  {
   InitializeComponent();
    thread;
   string[] users = new string[] { "zkk", "admin", "administrator", "soft", "iany", "nec", "necsl" };
   for (int i = 0; i < ; i++)
   {
    thread = new (new (WriteLock));
    (users[i]);
   }
  }
  public void WriteThread(object user)
  {
   string path =  + "\\app\\";
   if (!(path))
    (path);
   path = path + "\\" + ("yyyyMMdd") + ".txt";
   StringBuilder sb = new StringBuilder();
   ("----------------------------" + ("yyyy-MM-dd HH:mm:") + "--------------------------");
   (());
   ("---------------------------------------------------------------------------------");
   ();
   //if (!(path))
   // (path).Close();
    fileStream = new (path, , , );
    sw = new (fileStream, );
   (());
   ();
   ();
   ();
   ();
  }
  public void WriteLock(object user)
  {
   lock (obj)
   {
    string path =  + "\\app\\";
    if (!(path))
     (path);
    path = path + "\\" + ("yyyyMMdd") + ".txt";
    StringBuilder sb = new StringBuilder();
    ("----------------------------" + ("yyyy-MM-dd HH:mm:") + "--------------------------");
    (());
    ("---------------------------------------------------------------------------------");
    ();
    if (!(path))
     (path).Close();
     fileStream = new (path, , );
     sw = new (fileStream, );
    (());
    ();
    ();
    ();
    ();
   }
  }
 }
}

I hope this article will be helpful to everyone's C# programming.