使用信号量机制来实现对资源的独占访问

https://www.cnblogs.com/myprogram/p/4931164.html

 

复制代码
    public static class LogHelper
    {
        private static readonly ConcurrentQueue<LogModel> _que = new ConcurrentQueue<LogModel>();

        private static readonly ManualResetEvent _mre = new ManualResetEvent(false);

        private static Thread _thread = new Thread(new ThreadStart(WriteLog)) { IsBackground = true, Priority = ThreadPriority.BelowNormal };
public static void WriteLogForCustom(string log)
        {
            _que.Enqueue(new LogModel
            {
                Message = $"{log}\r\n",
                Path = "logs/",
                FileName = DateTime.Now.ToString("yyyy_MM_dd") + ".log"
            });
            _mre.Set();
        }
/// <summary>
        /// 启动日志线程
        /// </summary>
        public static void Register()
        {
            try { _thread.Abort(); } catch { }
            _thread.Start();
        }

        private static void WriteLog()
        {
            while (true)
            {
                _mre.WaitOne();
                while (_que.Count > 0 && _que.TryDequeue(out LogModel log))
                {
                    string dirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, log.Path);
                    if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);
                    string filePath = Path.Combine(dirPath, log.FileName);
                    if (!File.Exists(filePath)) File.Create(filePath).Close();
                    File.AppendAllText(filePath, log.Message);
                }
                _mre.Reset();
                Thread.Sleep(1);
            }
        }
    }

    public class LogModel
    {
        /// <summary>
        /// 目录
        /// </summary>
        public string Path { get; set; }

        /// <summary>
        /// 文件名
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// 信息
        /// </summary>
        public string Message { get; set; }
    }
复制代码

 

posted @   竹林听雨行  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2021-03-08 ASP.NET Core 配置跨域(CORS)
点击右上角即可分享
微信分享提示