Task之TaskFactory

1.经过任务开启线程
1.1 建立Task对象
首先建立任务对象,任务对象调用Start()方法开启任务线程。

class Program
{
    static void DownLoad(object str)
    {
        Console.WriteLine("DownLoad Begin ID = " + Thread.CurrentThread.ManagedThreadId + " " + str);
        Thread.Sleep(1000);
        Console.WriteLine("DownLoad End");
    }
    static void Main(string[] args)
    {
        //建立任务
        Task task = new Task(DownLoad, "人民日报");
        //启动任务
        task.Start();
        Console.WriteLine("Main");   
        Console.ReadKey();
    }
}

 

 

1.2 任务工厂TaskFactory

      首先建立任务工厂,而后调用StartNew()方法开启任务线程。

class Program
{
    static void DownLoad(object str)
    {
        Console.WriteLine("DownLoad Begin ID = " + Thread.CurrentThread.ManagedThreadId + " " + str);
        Thread.Sleep(1000);
        Console.WriteLine("DownLoad End");
    }
    static void Main(string[] args)
    {
        //建立任务工厂
        TaskFactory taskFactory = new TaskFactory();
        //开始新的任务
        taskFactory.StartNew(DownLoad, "纽约时报");
        Console.WriteLine("Main");
        Console.ReadKey();
    }
}

 

posted @ 2021-05-24 10:27  ProZkb  阅读(1057)  评论(1编辑  收藏  举报