UdpLoggerSender.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace MeterVision.Helper
  12. {
  13. public class UdpLoggerSender
  14. {
  15. private static UdpLoggerSender _instance;
  16. private static readonly object _lock = new object();
  17. private readonly ConcurrentQueue<string> _logQueue = new ConcurrentQueue<string>(); // 日志队列
  18. private readonly CancellationTokenSource _cts = new CancellationTokenSource();
  19. private readonly Task _logTask;
  20. private readonly UdpClient _udpClient;
  21. private readonly IPEndPoint _remoteEndPoint;
  22. private UdpLoggerSender(string ip, int port)
  23. {
  24. // 初始化 UDP 发送端
  25. _udpClient = new UdpClient();
  26. _remoteEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
  27. // 启动后台任务,异步处理日志队列
  28. _logTask = Task.Run(ProcessLogQueue, _cts.Token);
  29. }
  30. public static UdpLoggerSender GetInstance(string ip = "127.0.0.1", int port = 5000)
  31. {
  32. if (_instance == null)
  33. {
  34. lock (_lock)
  35. {
  36. if (_instance == null)
  37. _instance = new UdpLoggerSender(ip, port);
  38. }
  39. }
  40. return _instance;
  41. }
  42. /// <summary>
  43. /// 添加日志到队列(调用频繁,不会创建新线程)
  44. /// </summary>
  45. public void EnqueueLog(string message)
  46. {
  47. _logQueue.Enqueue(message);
  48. }
  49. /// <summary>
  50. /// 后台任务,循环处理日志队列,异步发送日志
  51. /// </summary>
  52. private async Task ProcessLogQueue()
  53. {
  54. while (!_cts.Token.IsCancellationRequested)
  55. {
  56. if (_logQueue.TryDequeue(out string logMessage))
  57. {
  58. try
  59. {
  60. await SendLogAsync(logMessage);
  61. }
  62. catch (Exception ex)
  63. {
  64. Debug.WriteLine($"日志发送失败: {ex.Message}");
  65. }
  66. }
  67. else
  68. {
  69. // 队列为空时稍作等待,避免 CPU 100%
  70. await Task.Delay(10);
  71. }
  72. }
  73. }
  74. /// <summary>
  75. /// 通过 UDP 发送日志
  76. /// </summary>
  77. private async Task SendLogAsync(string message)
  78. {
  79. byte[] data = Encoding.UTF8.GetBytes(message);
  80. await _udpClient.SendAsync(data, data.Length, _remoteEndPoint);
  81. //Debug.WriteLine($"UDP 发送: {message}");
  82. }
  83. /// <summary>
  84. /// 释放资源
  85. /// </summary>
  86. public void Stop()
  87. {
  88. _cts.Cancel();
  89. _logTask.Wait();
  90. _udpClient.Close();
  91. }
  92. //----------------------------------------------------------
  93. }
  94. }