使用队列处理并发写入文件操作

*.txt 文档是我在代码中最常用的文档操作对象,我会把我的操作信息,以及错误信息等等,都保存在我的demo下的某个.txt文件中,这样,我很容易查看到,程序默默地方出错,或者,我操作过哪里。

简单形式:

string filePath = @"d://log.txt";
File.AppendAllText(filePath, e.StackTrace + "
-***********************************************************
");

在保存文档txt时,我通常都不妨在c盘,怕系统报我权限不足引起程序出错

这样的两个代码,就能保证我把信息,写入到我指定的文档中

加锁形式:

lock ("abc")
{
          
   string filePath = @"d://log.txt";
   File.AppendAllText(filePath, e.StackTrace + "
-------------------------------------------------------
");
}

“adc”利用字符串作为lock 的对象,利用字符串的不可变性。

这样就解决了,脏数据的问题,也就是,每次只能一个人访问 log.txt文档,当写完数据后,另一段代码,才能继续写入。(这无形中延迟了代码的响应时长,这也是不明智,当然,数据是直接写入磁盘,对于性能来说,肯定没放在内存中的好)

队列形式:

Thread thread = new Thread(() =>
            {
                while (true)
                {
                    if (queue.Count > 0)
                    {
                        string filePath = @"d://log.txt";
                        File.AppendAllText(filePath, queue.Dequeue());
                    }
                    else
                    {
                        Thread.Sleep(5000);
                    }
                }
               
            });

            thread.IsBackground = true;
            thread.Start();

利用多线程,不阻塞当前主线程;queue.Dequeue() ,队列消息的读取(先加入,才能读)

我单开的线程,只有Start()方法,没有end ,这意味着,只有电脑宕机了,这个方法才结束,所以,加个死循环,不定期问问当前的队列对象,你里面有没有数据啊,要是没有的话,就让当前线程休息5秒钟,然后再问。

完整的loghelper代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ZY.Blog.Common
{
    public class LogHelper
    {
        private static Queue<string> queue = new Queue<string>();
        public static void WriteLog(Exception e)
        {
            queue.Enqueue(e.StackTrace+"
------------------------------------------------------
");
        }

        //静态构造方法
        static LogHelper()
        {
            SaveLog();
        }

        public static void SaveLog()
        {
            Thread thread = new Thread(() =>
            {
                while (true)
                {
                    if (queue.Count > 0)
                    {
                        string filePath = @"d://a.txt";
                        File.AppendAllText(filePath, queue.Dequeue());
                    }
                    else
                    {
                        Thread.Sleep(5000);
                    }
                }
               
            });

            thread.IsBackground = true;
            thread.Start();

        }
    }
}
原文地址:https://www.cnblogs.com/zychengzhiit1/p/4715061.html