欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

C#连续任务Task.ContinueWith方法

时间:2022-12-20 10:11:39|栏目:.NET代码|点击:

一、简介

通过任务,可以指定在任务完成之后,应开始运行之后另一个特定任务。ContinueWith是Task根据其自身状况,决定后续应该作何操作。也就是说,在运行完task后,会执行task.continuewith(XX)中的XX语句,但是是否执行、如何执行等需要看task的运行情况。例如:一个使用前一个任务的结果的新任务,如果前一个任务失败了,这个任务就应执行一些清理工作。任务处理程序都不带参数或者带一个对象参数,而任务的连续处理方法都有一个Task类型的参数。

二、案例

案例一:

代码:

        static int TaskMethod(string name, int seconds)
        {
            Console.WriteLine("Frist Task Method : Task {0} is running on a thread id: {1}. Is thread pool thread: {2}",
            name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            return 60 * seconds;
        }
        static void Main(string[] args)
        {

            var FirstTask = new Task<int>(() => TaskMethod("Frist Task", 3));
            FirstTask.ContinueWith(t => Console.WriteLine("Frist Task Result: {0}. Thread id: {1}, Is in Thred Pool: {2}",
            t.Result, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread),
            TaskContinuationOptions.OnlyOnRanToCompletion);//線程池線程
            FirstTask.Start();
           
            Console.ReadKey();
        }

结果:

Start()和ContinueWith()的先后顺序没有关系,ContinueWith()会等待直到firstTask运行状态达到 IsCompleted,因为TaskContinuationOptions中的OnlyOnRanToCompletion.必须指出的是,ContinueWith()中的参数是需要以Task为参数的,也就是firstTask作为参数被传入,而且ContinueWith()运行在线程池中的线程中。我觉得比较重要的一点是:把ContinueWith()中的语句当做一块新的语句块,他们独立于主线程。无论如何,他们都要被判断,如果状态(status)不满足,那么他们不执行;当指定了多个状态,则使用合理的对应状态。

案例二:

代码:

    class Program
    {
        static int TaskMethod(string name, int seconds)
        {
            Console.WriteLine("Task Method : Task {0} is running on a thread id: {1}. Is thread pool thread: {2}",
            name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            return 60 * seconds;
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Main Thread id {0}, Is in Thred Pool: {1}",
            Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);

            var firstTask = new Task<int>(() => TaskMethod("frist task", 3));
            var secondTask = new Task<int>(() => TaskMethod("second task", 2));

            firstTask.ContinueWith(t => Console.WriteLine("Result:Frist Thread Result: {0}. Thread id: {1}, Is in Thred Pool: {2}",
            t.Result, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread),
            TaskContinuationOptions.OnlyOnRanToCompletion);

            firstTask.Start();
            secondTask.Start();

            Thread.Sleep(TimeSpan.FromSeconds(4)); //给予足够时间,让firstTask、secondTask及其后续操作执行完毕。

            Task continuation = secondTask.ContinueWith(t => Console.WriteLine("Result:Second Thread Result: {0}. Thread id: {1}, Is in Thred Pool: {2}",
            t.Result, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread),
            TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously);
            Console.ReadLine();
            Console.ReadKey();
        }
    }

结果:

这里主线程休眠了足足4秒钟,足以让firstTask和secondTask两个任务完成运行,而后,由于secondTask的后续除了接受OnlyOnRanToCompletion外,还接受ExecuteSynchronously。因此,后续运行中,由于主线程还没有结束,因此 ExecuteSynchronously得到认可,故secondTask的后续是在主线程上运行。

案例三:

代码:

    class Program
    {
        static int TaskMethod(string name, int seconds)
        {
            Console.WriteLine("Task Method : Task {0} is running on a thread id: {1}. Is thread pool thread: {2}",
            name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            return 60 * seconds;
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Main Thread id {0}, Is in Thred Pool: {1}",
            Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);

            var firstTask = new Task<int>(() => TaskMethod("frist task", 3));
            var secondTask = new Task<int>(() => TaskMethod("second task", 2));

            firstTask.ContinueWith(t => Console.WriteLine("Result:Frist Thread Result: {0}. Thread id: {1}, Is in Thred Pool: {2}",
            t.Result, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread),
            TaskContinuationOptions.OnlyOnRanToCompletion);

            firstTask.Start();
            secondTask.Start();

           //Thread.Sleep(TimeSpan.FromSeconds(4)); //给予足够时间,让firstTask、secondTask及其后续操作执行完毕。

            Task continuation = secondTask.ContinueWith(t => Console.WriteLine("Result:Second Thread Result: {0}. Thread id: {1}, Is in Thred Pool: {2}",
            t.Result, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread),
            TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously);
            Console.ReadLine();
            Console.ReadKey();
        }
    }

结果:

然而,如果把4秒钟的休眠注释掉,那么由于主线程很早就结束了,因此secondTask只能接受到OnlyOnRanToCompletion,因此还是运行在线程池中。

上一篇:LINQ基础之Intersect、Except和Distinct子句

栏    目:.NET代码

下一篇:使用ASP.NET MVC 4 Async Action+jQuery实现消息通知机制的实现代码

本文标题:C#连续任务Task.ContinueWith方法

本文地址:http://www.codeinn.net/misctech/221770.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有