C#中的线程开启方式4-任务

xiaoxiao2021-02-28  22

任务开启

第一种方式

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 //任务开始 //任务结束
转载请注明原文地址: https://www.6miu.com/read-2631937.html

最新回复(0)