任务

任务


static void Main(string[] args)
{
    TaskFactory tf = new TaskFactory();
    Task t = tf.StartNew(Test);
    Thread.Sleep(5000);
}

static void Test()
{
    for (int i = 0; i < 10000; i++)
    {
        Console.WriteLine("A");
    }
}
static void Main(string[] args)
{
    Task t = new Task(Test);
    t.Start();
    Thread.Sleep(5000);
}

static void Test()
{
    for (int i = 0; i < 10000; i++)
    {
        Console.WriteLine("A");
    }
}

连续任务

如果一个任务t1的执行是依赖于另一个任务t2的,那么就需要在这个任务t2执行完毕后才开始执行t1。这个时候我们就可以使用连续任务。

static void FirstDownload()
{
    Console.WriteLine("Downloading ...");
    Thread.Sleep(2000);
}

static void SecondAlert(Task t)
{
    Console.WriteLine("下载完成!");
}

static void Main(string[] args)
{
    Task t1 = new Task(FirstDownload);
    t1.ContinueWith(SecondAlert);
    t1.Start();
    Thread.Sleep(5000);
}
static void FirstDownload()
{
    Console.WriteLine("Downloading ...");
    Thread.Sleep(2000);
}

static void SecondAlert(Task t)
{
    Console.WriteLine("下载完成!");
}

static void Main(string[] args)
{
    Task t1 = new Task(FirstDownload);
    Task t2 = t1.ContinueWith(SecondAlert);
    Task t3 = t2.ContinueWith(SecondAlert);
    t1.Start();
    Thread.Sleep(5000);
}
posted @ 2023-10-04 15:54  天空之城00  阅读(15)  评论(0)    收藏  举报