C# Thread test demo

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            /*
             一个进程可以创建一个或多个线程以执行与该进程关联的部分程序代码。在C#中,线程是使用Thread类处理的,该类在System.Threading命名空间中。
             使用Thread类创建线程时,只需要提供线程入口,线程入口告诉程序让这个线程做什么。通过实例化一个Thread类的对象就可以创建一个线程。
             创建新的Thread对象时,将创建新的托管线程。Thread类接收一个ThreadStart委托或ParameterizedThreadStart委托的构造函数,该委托包装了调用Start方法时由新线程调用的方法,示例代码如下:

             */
            //调用无参数的方法
            Thread thread = new Thread(new ThreadStart(ProcessAndThread));
            thread.Start();

            //通过匿名委托创建的线程
            Thread thread1 = new Thread(delegate () { WriteLog(string.Empty, null, "我是通过匿名委托创建的线程"); });
            thread1.Start();
            //通过Lambda表达式创建的委托
            Thread thread2 = new Thread(() => WriteLog(string.Empty, null, "我是通过Lambda表达式创建的委托"));
            thread2.Start();
        }

        protected void ProcessAndThread()
        {

            string[] lines = { "First line", "Second line", "Third line" };
            WriteLog(string.Empty, lines, string.Empty);

            string text = "A class is the most powerful data type in C#. Like a structure, " + "a class defines the data and behavior of the data type. ";
            WriteLog(string.Empty, null, text);
        }

        protected void WriteLog(string pre, string[] lines, string logContent)
        {
            string dir = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\log\\";
            dir = AppDomain.CurrentDomain.BaseDirectory + "\\log\\";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            if (string.IsNullOrEmpty(pre))
            {
                pre = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + " ";
            }
            string logFileUrl = Path.Combine(dir, DateTime.Now.ToString("yyyyMMdd") + ".log");
            if (!File.Exists(logFileUrl))
            {
                File.Create(logFileUrl).Close();
            }
            if (lines != null)
            {
                File.AppendAllLines(logFileUrl, lines);
            }
            //if (!string.IsNullOrEmpty(logContent))
            //{
            File.AppendAllText(logFileUrl, pre + logContent);
            //}
        }

    }
View Code
发布了259 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/hofmann/article/details/104058217