创建线程

一)使用Thread类

ThreadStart threadStart=new ThreadStart(method1);//通过ThreadStart委托告诉子线程讲执行什么方法,这里执行一个 方法
Thread thread=new Thread(threadStart);
thread.Start(); //启动新线程

public void method1(){

}

二)使用Delegate.BeginInvoke

delegate bool d_CheckAge(int age); //申明一个委托,表明需要在子线程上执行的方法的函数签名
static d_CheckAge dca= new d_CheckAge(CheckAgeMethod);//把委托和具体的方法关联起来
static void Main(string[] args)
{
//此处开始异步执行,并且可以给出一个回调函数(如果不需要执行什么后续操作也可以不使用回调)
dca.BeginInvoke(5, new AsyncCallback(TaskFinished), null);
Console.ReadLine();
}

//线程调用的函数,给出
public static bool CheckAgeMethod(int age)
{
return age>20?true:false
}

//线程完成之后回调的函数
public static void TaskFinished(IAsyncResult result)
{
bool re = false;
re = calcMethod.EndInvoke(result);
Console.WriteLine(re);
}

三)使用ThreadPool.QueueworkItem

WaitCallback w = new WaitCallback(CheckAgeMethod);
//下面启动四个线程,计算四个直径下的圆周长
ThreadPool.QueueUserWorkItem(w, 11);
ThreadPool.QueueUserWorkItem(w, 22);
ThreadPool.QueueUserWorkItem(w, 32);
ThreadPool.QueueUserWorkItem(w, 44);
public static void CheckAgeMethod(int age)
{
Console.ReadLine(age);
}

原文地址:https://www.cnblogs.com/mmbbflyer/p/8136525.html