C#多线程写入日志

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp5
{
    class Program
    {
        public delegate void AsyncLog(string str1, string str2);
        public static object lockObject = new object();
        static void Main(string[] args)
        {

            Test(); 
            Console.ReadLine();
        }
        public static void Test()
        {
            Console.WriteLine("Test Start...");

            for (int i = 0; i < 10; i++)
            {
                AsyncLog asyLog1 = new AsyncLog(WriteLog);
                asyLog1.BeginInvoke("EventActionA" + i.ToString(), "EventContentA" + i.ToString(), null, null);

                AsyncLog asyLog2 = new AsyncLog(WriteLog);
                asyLog2.BeginInvoke("EventActionB" + i.ToString(), "EventContentB" + i.ToString(), null, null);

                AsyncLog asyLog3 = new AsyncLog(WriteLog);
                asyLog3.BeginInvoke("EventActionC" + i.ToString(), "EventContentC" + i.ToString(), null, null);
            }

            Console.WriteLine("Test End...");
        }
        private static void WriteLog(string strEventType, string strEventContent)
        {
            lock (lockObject)
            {
                Console.WriteLine("Write Log start... ThreadID:{0}", Thread.CurrentThread.ManagedThreadId);

                //string strLogPath = string.Format("D:\\Log\\Log{0}.log", DateTime.Now.ToString("yyyy-MM-dd"));

                //if (!File.Exists(strLogPath))
                //{
                //    File.Create(strLogPath).Close();
                //}

                //FileStream fs = new FileStream(strLogPath, FileMode.Append, FileAccess.Write);
                //StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);

                //sw.WriteLine(string.Format("{0}  {1}", strEventType, strEventContent));

                //sw.Close();
                //fs.Close();

                Console.WriteLine("Write Log End   ThreadID:{0},type:{1}", Thread.CurrentThread.ManagedThreadId, strEventType);
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值