Created
June 14, 2021 11:15
-
-
Save ruyut/2919c87667fcd3752b1d43a90482e79c to your computer and use it in GitHub Desktop.
使用Timer定時輸出全部Log,避免重複開關檔案影響效能
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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