欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-08-17 16:18:59
本文实例讲述了c#实现多线程写入同一个文件的方法。分享给大家供大家参考。具体实现方法如下: namespace wfpapp { public partia...

本文实例讲述了c#实现多线程写入同一个文件的方法。分享给大家供大家参考。具体实现方法如下:

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#程序设计有所帮助。