C# 队列(Queue)解决简单并发

日志例子:

        private static Queue<string> m_Message = new Queue<string>();
        private static bool m_IsRunning;
     public  void LogResult2(string sWord)
        {
            lock (m_Message)
            {
                //将日志加入到队列中
                m_Message.Enqueue(sWord);
            }
            //判断打印日志的方法是否在跑
            if (!m_IsRunning)
            {
                m_IsRunning = true;
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    Print();
                });
            }
        }
        //打印日志
        private static void Print()
        {
            while (true)
            {
                var messge = string.Empty;
                lock (m_Message)
                {
                    //队列里的条数为0时,跳出
                    if (m_Message.Count == 0)
                    {
                        m_IsRunning = false;
                        return;
                    }
                    //取出队列里的值
                    messge = m_Message.Dequeue();
                    string filePath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                    FileStream fs = new FileStream(filePath, FileMode.Append);
                    StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
                    sw.Write(messge);
                    sw.Close();
                    fs.Close();
                }
            }
        }

 

posted @ 2016-12-22 14:34    阅读(4619)  评论(0编辑  收藏  举报