方法一:使用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;
}