C# .net 集合-并发处理之文件读写处理

//读写锁,当资源处于写入模式时,其他线程写入需要等待本次写入结束之后才能继续写入
 static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
 //设置读写锁为写入模式独占资源,其他写入请求需要等待本次写入结束之后才能继续写入
                //注意:长时间持有读线程锁或写线程锁会使其他线程发生饥饿 (starve)。 为了得到最好的性能,需要考虑重新构造应用程序以将写访问的持续时间减少到最小。
                //      从性能方面考虑,请求进入写入模式应该紧跟文件操作之前,在此处进入写入模式仅是为了降低代码复杂度
                //      因进入与退出写入模式应在同一个try finally语句块内,所以在请求进入写入模式之前不能触发异常,否则释放次数大于请求次数将会触发异常
                LogWriteLock.EnterWriteLock();

static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
//写log文件
public void WriteLog()
{
string SDate = Program.SpiderDate;
//创建文件夹
string Path = “Log\” + SDate;
if (!Directory.Exists(Path))
{
Directory.CreateDirectory(Path);
}
string logName = “Log\” + SDate + “\” + SDate + “.txt”;
int len = 0;

        Parallel.ForEach<LogEntity>(Program.LogList.GetConsumingEnumerable(), logEntity =>
       //foreach (LogEntity logEntity in Program.LogList.GetConsumingEnumerable())
       {
           try
           {
               LogWriteLock.EnterWriteLock();
               using (StreamWriter sw = new StreamWriter(logName, true, Encoding.Default))
               {

                   sw.WriteLine(logEntity.STime);
                   sw.WriteLine(logEntity.Content);



               }
           }
           catch (FileNotFoundException fileCe)
           {
               throw fileCe;
           }
           catch (Exception ce)
           {
               throw ce;
           }
           finally
           {
               //退出写入模式,释放资源占用

               LogWriteLock.ExitWriteLock();
           }

       });



    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值