Queue 队列 写日志简单应用

public class LogContent
    {
        public LogContent()
        {
           
        }
        public LogContent(string msg)
        {
            this.Message = msg;
        }
        private string mssage;
        public string Message
        {
            get;
            set;
        }
    }

public static class FileQueueManager
    {
        private static object lockHelper = new object();
        static Thread workerThread;
        static FileQueueManager()
        {
            workerThread = new Thread(new ThreadStart(Run));
            workerThread.Start();
        }
        private static Queue<LogContent> logMessageQueue = new Queue<LogContent>();

        public static void Write(LogContent log)
        {
            lock (lockHelper)
            {
                logMessageQueue.Enqueue(log);
            }
        }
        public static int QueueCount
        {
            get { return logMessageQueue.Count; }
        }
        private static void Run()
        {
            lock (lockHelper)
            {
                Write(new LogContent() { Message = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") });
            }
            LogContent log;
            while (true)
            {
                try
                {
                    if (logMessageQueue.Count > 0)
                    {
                        Write();
                        lock (lockHelper)
                        {
                            logMessageQueue.Dequeue();
                        }
                    }
                    else
                        break;
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {

                }
            }
        }
        private static void Write()
        {
            string logdir;
            //logdir = System.Web.HttpContext.Current.Server.MapPath(logFileName);
            logdir = @"d:\a.log";
            try
            {
                System.IO.StreamWriter sw = new System.IO.StreamWriter(logdir, true);
                sw.BaseStream.Seek(0, System.IO.SeekOrigin.End);
                sw.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + DateTime.Now.Millisecond + "]" + workerThread.ManagedThreadId + "");
                sw.Flush();
                sw.Close();
            }
            catch (Exception e)
            {

            }
        }

    }

private static void ThreadQueueTest()
        {
            for (int i = 0; i < 100; i++)
                FileQueueManager.Write(new LogContent() { Message = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") });
            System.Console.WriteLine(FileQueueManager.QueueCount);
        }

posted @ 2011-10-14 15:33  s80895304  阅读(367)  评论(0编辑  收藏  举报