• 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; }
    *****************************************************
    *** No matter how far you go, looking back is also necessary. ***
    *****************************************************
  • 相关阅读:
    Demo学习: DownloadDemo
    Demo学习: FileUpload
    Demo学习: Dialogs Anonymous Callback
    Demo学习: Cookies Demo
    Demo学习: CustomException
    Demo学习: Collapsible Panels
    Demo学习: ColumnSort
    Demo学习: ClientInfo
    Demo学习: Closable Tabs
    Demo学习: ClientEvents
  • 原文地址:https://www.cnblogs.com/gangle/p/9285094.html
Copyright © 2020-2023  润新知