gangle

怎样创建一个线程

 

方法一:使用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. ***
*****************************************************

分类:

技术点:

相关文章:

  • 2022-01-01
  • 2022-12-23
  • 2021-09-25
  • 2021-10-14
  • 2021-07-16
  • 2022-01-10
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-17
相关资源
相似解决方案