C# 多线程的创建

怎样创建一个线程

方法一:使用Thread类

   public static void Main(string[] args)
        {
            //方法一:使用Thread类
            ThreadStart threadStart = new ThreadStart(Calculate);//通过ThreadStart委托告诉子线程执行什么方法  
Thread thread = new Thread(threadStart);
thread.Start();//启动新线程 } public static void Calculate() { Console.Write("执行成功"); Console.ReadKey(); }

方法二:使用Delegate.BeginInvoke

   delegate double CalculateMethod(double r);//声明一个委托,表明需要在子线程上执行的方法的函数签名
     static CalculateMethod calcMethod = new CalculateMethod(Calculate);

   static void Main(string[] args)
     {
          //方法二:使用Delegate.BeginInvoke
          //此处开始异步执行,并且可以给出一个回调函数(如果不需要执行什么后续操作也可以不使用回调)
          calcMethod.BeginInvoke(5, new AsyncCallback(TaskFinished), null);
          Console.ReadLine();
     }

   public static double Calculate(double r)
     {
         return 2 * r * Math.PI;
     }
        //线程完成之后回调的函数
        public static void TaskFinished(IAsyncResult result)
        {
            double re = 0;
            re = calcMethod.EndInvoke(result);
            Console.WriteLine(re);
        }

方法三:使用ThreadPool.QueueworkItem

    WaitCallback w = new WaitCallback(Calculate);
    //下面启动四个线程,计算四个直径下的圆周长
    ThreadPool.QueueUserWorkItem(w, 1.0);
    ThreadPool.QueueUserWorkItem(w, 2.0);
    ThreadPool.QueueUserWorkItem(w, 3.0);
    ThreadPool.QueueUserWorkItem(w, 4.0);
    public static void Calculate(double Diameter)
    {
        return Diameter * Math.PI;
    }
扫描二维码关注公众号,回复: 2000390 查看本文章
*****************************************************
*** No matter how far you go, looking back is also necessary. ***
*****************************************************

猜你喜欢

转载自www.cnblogs.com/gangle/p/9285094.html