简体   繁体   English

C#中的简单线程安全的非阻塞文件记录器类

[英]Simple thread-safe non-blocking file logger class in c#

I have a web application, that will log some information to a file. 我有一个Web应用程序,它将一些信息记录到文件中。 I am looking for a simple thread-safe non-blocking file logger class in c#. 我正在寻找一个简单的线程安全的非阻塞文件记录器类在C#中。 I have little experience with threading. 我对线程处理的经验很少。 I known there are great logging components out there like log4Net, Enterprise Library Logging Block, ELMAH, but I do not want an external dependence for my application. 我知道那里有很棒的日志记录组件,例如log4Net,企业库日志记录块,ELMAH,但是我不希望我的应用程序具有外部依赖性。 I was thinking about using this queue implementation http://www.codeproject.com/KB/cpp/lockfreeq.aspx 我正在考虑使用此队列实现http://www.codeproject.com/KB/cpp/lockfreeq.aspx

如果您不想使用外部库,则可以使用Trace

The FileStream.BeginWrite method pushes the write operation onto a thread that's managed by the system. FileStream.BeginWrite方法将写入操作推送到系统管理的线程上。 That's the easy bit. 这很容易。

If you put your messages into a synchronized Queue, and have the EndWrite method pull the next item off the queue, then all your logging will be off-thread as far as the app is concerned. 如果将消息放入同步的Queue中,并使用EndWrite方法将下一个项目从队列中拉出,那么就应用程序而言,所有日志记录都将是线程外的。

The last step is to wrap putting messages onto the queue to set an event, so that if the queue is empty when EndWrite comes to look for the next message, it can wait for the event to be set. 最后一步是将消息包装到队列中以设置事件,以便当EndWrite来查找下一条消息时,如果队列为空,则可以等待事件被设置。

I've done a simple logging mechanism in my project in the office. 我在办公室的项目中完成了一个简单的日志记录机制。

I have a log class that is Shared (Static C#). 我有一个共享的日志类(静态C#)。

Inside this class I have a Synchronised Queue, and it has it's own thread. 在此类中,我有一个“同步队列”,它有自己的线程。

Then inside this thread, I just have it use a AutoresetEvent with your own defined WaitTime (i use 250ms). 然后在此线程中,我只是将它与您自己定义的WaitTime一起使用AutoresetEvent(我使用250ms)。

Then when this ResetEvent times out, I collect what is currently in the queue (using DeQueue) and write each on to the File. 然后,当此ResetEvent超时时,我(使用DeQueue)收集队列中当前的内容并将其写入文件。

Things to remember ... Have a class or struct that can hold the date when the Entry went in, rather than the time you wrote to disk, incase you choose a longer time to sleep your thread. 要记住的事情...有一个类或结构可以保存Entry进入的日期,而不是您写入磁盘的时间,以防您选择更长的时间使线程休眠。

If you want your application to exit quickly expose a method that will Set the Event to drop it out of the sleep and exit gracefully. 如果您想让应用程序快速退出,请公开一个方法,该方法将设置事件以使其退出睡眠状态并优雅地退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM