如何在多线程应用程序中执行文件记录

时间:2016-04-22 10:13:29

标签: c# multithreading logging

我需要一种极速快速记录方式(关于高速摄像机的帧信息)。 它只是我需要记录的几个数字,以及一个简单的file.log。 事件记录对此很慢。

然后我想,好吧,只需创建一个文件流,这样我就可以锁定我的应用程序的文件。并附加到它。

通常我会使用一个简单的行,例如

Filestream fs = new FileStream(@"D:\Log.csv", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);

在方法内。

然而,由于相机驱动程序的帧在新线程中执行,我在这里遇到了问题。因为我不希望每次写入日志文件时重新打开和关闭文件。 (打开和关闭很慢)。

我想在我的程序开始时打开一次日志文件,线程应该只对它执行写操作,而不是一次又一次地关闭和打开它。

如何实现这一点,因为这不起作用:

using System.IO;
FileStream fs = new FileStream(@"D:\Log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);

    static void Main(string[] args)
    {
         // doing it in main doesn't work either.
         fs = new FileStream(@"D:\Log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
       //...
       //.. init camera and start camera lots of code follows but is not related to the question.
     }

     Camera_Thread.FrameArrived (FrameArrivedEventArgs e)
    {   
       byte[] n = MyFilterFunction(e.frame);         
       fs.WriteByte(MyArrayToString(n));
    }

1 个答案:

答案 0 :(得分:1)

有很多方法,但大多数方法都涉及排队,尤其是在多线程环境中。

您可以使用MSMQ对日志进行排队处理,也可以使用单独的线程处理内存中队列中的日志。

string logFile = "Log.txt";
this.Queue = new ConcurrentQueue<string>();

var thread = new Thread(() => 
{
    string log;

    while (true)
    {
        while (!this.Queue.IsEmpty)
        {
            if (!this.Queue.TryDequeue(out log)) continue;

            File.AppendAllText(logFile, "\n" + log);
        }

        Thread.Sleep(1000);
    }

});

thread.Start();

此实现没有考虑如何取消日志记录线程,因此我将让您首先尝试自己尝试。我还要补充一点,这不是很可靠,鉴于选择,我实际上使用的是MSMQ。

相关问题