Skip to content

Instantly share code, notes, and snippets.

@ruyut
Created June 14, 2021 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruyut/2919c87667fcd3752b1d43a90482e79c to your computer and use it in GitHub Desktop.
Save ruyut/2919c87667fcd3752b1d43a90482e79c to your computer and use it in GitHub Desktop.
使用Timer定時輸出全部Log,避免重複開關檔案影響效能
using System.Collections.Generic;
using System.IO;
using System.Timers;
namespace Ruyut
{
public class TimerLog
{
private static System.Timers.Timer _timer;
private static readonly string FileName = "D:\\log.log";
private static void TimerInit()
{
if (_timer == null)
{
_timer = new System.Timers.Timer();
_timer.Interval = 1000;
_timer.AutoReset = true;
_timer.Elapsed += new System.Timers.ElapsedEventHandler(Print);
_timer.Start();
}
}
private static void Print(object sender, ElapsedEventArgs e)
{
Print();
}
private static Queue<string> _queue = new Queue<string>();
private static void Print()
{
if (_queue.Count == 0) return;
_timer.Stop();
using (StreamWriter streamWriter = new StreamWriter(FileName, true))
{
for (int i = 0; i < _queue.Count; i++)
{
streamWriter.WriteLine(_queue.Dequeue().ToString());
}
streamWriter.Close();
}
_timer.Start();
}
private static void Write(string logMessage)
{
TimerInit();
_queue.Enqueue(logMessage);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment