码迷,mamicode.com
首页 > Windows程序 > 详细

C# Thread、lock

时间:2018-12-05 16:28:35      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:color   ati   代码   writer   start   static   按键   object   message   

    class Program
    {
        private static readonly object obj = new object();

        static void Main(string[] args)
        {
            Thread th1 = new Thread(TestLock);
            Thread th2 = new Thread(TestLock1);
            th1.IsBackground = true;
            th2.IsBackground = true;
            th2.Start();
            th1.Start();

            #region 按任意键继续

            Console.Write("按任意键继续!");
            //此代码会提示用户按任意键,然后在用户按键前暂停程序。
            Console.ReadKey(true);

            #endregion 按任意键继续
        }

        private static void TestLock()
        {
            lock (obj)
            {
                for (int i = 0; i < 10000; i++)
                {
                    var message = i.ToString();
                    string logFileName = @"F:\Log\" + DateTime.Now.ToString("yyyyMMdd") + "Log" + ".txt";
                    StreamWriter sr = new StreamWriter(logFileName, true);
                    try
                    {
                        sr.WriteLine(message);
                    }
                    catch
                    {
                        Console.WriteLine(message);
                    }
                    finally
                    {
                        sr.Close();
                    }
                }
            }
        }

        private static void TestLock1()
        {
            lock (obj)
            {
                for (int i = 10000; i < 20000; i++)
                {
                    var message = "Count:" + i.ToString();
                    string logFileName = @"F:\Log\" + DateTime.Now.ToString("yyyyMMdd") + "Log" + ".txt";
                    StreamWriter sr = new StreamWriter(logFileName, true);
                    try
                    {
                        sr.WriteLine(message);
                    }
                    catch
                    {
                        Console.WriteLine(message);
                    }
                    finally
                    {
                        sr.Close();
                    }
                }
            }
        }

        
    }

 

C# Thread、lock

标签:color   ati   代码   writer   start   static   按键   object   message   

原文地址:https://www.cnblogs.com/gygtech/p/10070674.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!