C#多线程Thread

在项目中经常用到线程Thread,先做个简单记录,后面再完善下,方便以后参考。本人技术有限,如有不同见解之处,欢迎博友批评指正。

执行的线程Thread分无参数的,一个参数,多个参数的。直接看代码吧。

NetFramework4.0后,出现了Task(本质还是Thread),这个效率更高,分配资源更合理。

一、没有参数的

        static void Main(string[] args)
        {
            Console.WriteLine("主线程开始了...");
            Console.WriteLine("主线程Thread:"+Thread.CurrentThread.ManagedThreadId);
            Thread thread = new Thread(ThreadTestMthod);
            thread.Start();
            for (int i = 0; i < 50; i++)
            {
                Console.WriteLine("Num:"+i);
            }
            
            Console.ReadKey();
        }
        static void ThreadTestMthod()
        {
            Console.WriteLine("当前线程Thread:"+Thread.CurrentThread.ManagedThreadId);
            for (int i = 50; i < 100; i++)
            {
                Console.WriteLine("Num:"+i);
            }
        }
View Code

二、一个参数

        static void Main(string[] args)
        {
            Console.WriteLine("主线程开始了...");
            Console.WriteLine("主线程Thread:" + Thread.CurrentThread.ManagedThreadId);
            Thread threadParam = new Thread(ThreadTestMthodParam);
            //或者Thread threadPapam2 = new Thread(new ThreadStart(() => ThreadTestMthodParam(100)));
            //再或者 Thread threadPapam3 = new Thread(() => ThreadTestMthodParam(100));
            threadParam.Start(100);

            for (int i = 0; i < 50; i++)
            {
                Console.WriteLine("Num:" + i);
            }

            Console.ReadKey();
        }
  static void ThreadTestMthodParam(object n)
        {
            int num = Convert.ToInt32(n);
            Console.WriteLine("有1个参数Thread:" + Thread.CurrentThread.ManagedThreadId);
            for (int i = 50; i < num; i++)
            {
                Console.WriteLine("Num:" + i);
            }
        }
View Code

三、多个参数

其实看到上面你也想到了,可以利用后面的Lambda表达式来表示。

        static void Main(string[] args)
        {
            Console.WriteLine("主线程开始了...");
            Console.WriteLine("主线程Thread:" + Thread.CurrentThread.ManagedThreadId);
            Thread threadParams = new Thread(() => ThreadTestMthodParams(100, 200));
            //或者Thread threadParams = new Thread(new ThreadStart(() => ThreadTestMthodParams(100, 200)));

            threadParams.Start();

            for (int i = 0; i < 50; i++)
            {
                Console.WriteLine("Num:" + i);
            }

            Console.ReadKey();
        }
        static void ThreadTestMthodParams(int min, int max)
        {
            Console.WriteLine("多个参数Thread:" + Thread.CurrentThread.ManagedThreadId);
            for (int i = min; i < max; i++)
            {
                Console.WriteLine("Num:" + i);
            }
        }
View Code

 用Task来操作

            Task t1 = new Task(ThreadTestMthod);
            t1.Start();

            Task t2 = new Task(() => ThreadTestMthodParams(100,200));
            t2.Start();
原文地址:https://www.cnblogs.com/MrBlackJ/p/8308648.html