第一种方式
class Program { static void ThreadMethod() { Console.WriteLine("任务开始"); Thread.Sleep(2000); Console.WriteLine("任务结束"); } static void Main() { Task t = new Task(ThreadMethod);//传递一个需要线程来执行的方法 t.Start(); Console.WriteLine("Main"); } } //输出为: //Main //任务开始 //任务结束第二种方式
class Program { static void ThreadMethod() { Console.WriteLine("任务开始"); Thread.Sleep(2000); Console.WriteLine("任务结束"); } static void Main() { TaskFactory tf = new TaskFactory();//使用工厂模式,便于多次创建,只需要调用StartNew即可 Task t = tf.StartNew(ThreadMethod); t.Start(); Console.WriteLine("Main"); } } //输出为: //Main //任务开始 //任务结束