Csharp/C#教程:C#实现多线程写入同一个文件的方法分享

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

namespaceWfpApp { publicpartialclassForm2:Form { objectobj=newobject(); publicForm2() { InitializeComponent(); System.Threading.Threadthread; string[]users=newstring[]{"zkk","admin","administrator","soft","iany","nec","necsl"}; for(inti=0;i<users.Length;i++) { thread=newSystem.Threading.Thread(newSystem.Threading.ParameterizedThreadStart(WriteLock)); thread.Start(users[i]); } } publicvoidWriteThread(objectuser) { stringpath=System.Windows.Forms.Application.StartupPath+"\app\"; if(!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); path=path+"\"+DateTime.Now.ToString("yyyyMMdd")+".txt"; StringBuildersb=newStringBuilder(); sb.AppendLine("----------------------------"+DateTime.Now.ToString("yyyy-MM-ddHH: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.FileStreamfileStream=newSystem.IO.FileStream(path,System.IO.FileMode.Append,System.IO.FileAccess.Write,System.IO.FileShare.ReadWrite); System.IO.StreamWritersw=newSystem.IO.StreamWriter(fileStream,Encoding.Default); sw.Write(sb.ToString()); sw.Close(); sw.Dispose(); fileStream.Close(); fileStream.Dispose(); } publicvoidWriteLock(objectuser) { lock(obj) { stringpath=System.Windows.Forms.Application.StartupPath+"\app\"; if(!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); path=path+"\"+DateTime.Now.ToString("yyyyMMdd")+".txt"; StringBuildersb=newStringBuilder(); sb.AppendLine("----------------------------"+DateTime.Now.ToString("yyyy-MM-ddHH: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.FileStreamfileStream=newSystem.IO.FileStream(path,System.IO.FileMode.Append,System.IO.FileAccess.Write); System.IO.StreamWritersw=newSystem.IO.StreamWriter(fileStream,Encoding.Default); sw.Write(sb.ToString()); sw.Close(); sw.Dispose(); fileStream.Close(); fileStream.Dispose(); } } } }

希望本文所述对大家的C#程序设计有所帮助。

您可能感兴趣的文章:c#使用多线程的几种方式示例详解c#winform多线程的小例子c#中多线程访问winform控件的若干问题小结c#多线程中Lock()关键字的用法小结浅解关于C#多线程的介绍C#队列Queue多线程用法实例c#多线程编程基础c#多线程的应用全面解析c#.net多线程编程教学——线程同步C#中的多线程小试牛刀

标签: 线程 多线程 方法

C++利用std::forward_list查找插入数据方法示例

C++数据精度问题(对浮点数保存指定位小数)

上述就是C#学习教程:C#实现多线程写入同一个文件的方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/906750.html

(0)
上一篇 2021年10月24日
下一篇 2021年10月24日

精彩推荐