多线程(一)

线程被一个线程协调程序(一个CRL委托给操作系统的程序)管理着。线程协调程序确保将所有活动着的线程分配适当的执行时间,并且等待或阻止的线程是不消耗CPU资源的。

线程用Thread类来创建, 通过ThreadStart委托来指明方法从哪里开始运行。

public delegate void ThreadStart();

 static void Main(string[] args)
        {
            // Thread t = new Thread(new ThreadStart(Go));
            Thread t = new Thread(Go);//与上一行等同
            t.Start();
            Console.Read();
        }

        static void Go()
        {
            Console.WriteLine("hello");
        }

接受参数的委托方法:public delegate void ParameterizedThreadStart(object obj);

{
            Program p = new Program();
            //Thread t = new Thread(new ParameterizedThreadStart(p.Go));
            Thread t = new Thread(p.Go);//与上一行等同
            t.Start("rxm");
            Console.Read();
        }

        void Go(object s)
        {
            Console.WriteLine(s.ToString());
        }

线程可以通过Name属性进行命名,只能设置一次,重命名会引发异常。

 static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "main";
            Go();
            Thread t = new Thread(Go);
            t.Name = "go";
            t.Start(); 
            Console.Read();
        }

        static void Go()
        {
            Console.WriteLine("当前的线程名字是:" + Thread.CurrentThread.Name);
        }

从.NET2.0开始,任何线程内未处理的异常都将导致程序关闭。为了避免由于异常引起的程序崩溃,需要在每个线程进入的方法内进行try/catch.

原文地址:https://www.cnblogs.com/hometown/p/3238759.html