Task explore cancellation (2)

In the previous blog exploring the cancellation Task _c # _ Huangteng Xiao's blog -CSDN blog describes task.run need to take the initiative to call during execution method ThrowIfCancellationRequested () to cancel, this time we study other cases of cancellation scene


Task .Delay

We know that Task.Dealythere is a heavy load can be passed CancellationToken, we make the following experiment

        static void Main(string[] args)
        {
            var source = new CancellationTokenSource();
            Foo(source.Token);
            Thread.Sleep(TimeSpan.FromSeconds(3));
            source.Cancel();
            Console.WriteLine("取消任务");
            Console.ReadLine();
        }

        public static void Foo(CancellationToken token)
        {
            Task.Delay(TimeSpan.FromSeconds(5), token)
                .ContinueWith(task => Console.WriteLine(task.Status));
        }

And similar experiments before, only Task.Runreplaced Task.Delay. The results shown in FIG.

Here Insert Picture Description

Visible Task.Delaydirect response canceled

Parallel

Again we Paralleldo experiments

        static void Main(string[] args)
        {
            var source = new CancellationTokenSource();
            Foo(source.Token);
            Thread.Sleep(TimeSpan.FromSeconds(3));
            source.Cancel();
            Console.WriteLine("取消任务");
            Console.ReadLine();
        }

        public static void Foo(CancellationToken token)
        {
            var options = new ParallelOptions()
            {
                CancellationToken = token,
            };
            Task.Run(() =>
            {
                Parallel.For(0, 10, options, (i, state) =>
                {
                    Console.WriteLine($"{i}任务开始");
                    Thread.Sleep(TimeSpan.FromSeconds(5));
                    Console.WriteLine($"{i}任务结束");
                });
            });
        }

By Parallel.Forcreate 10 parallel tasks, each task takes 5 seconds to cancel the task for the first three seconds. The results shown in FIG.

Here Insert Picture Description

Visible Parallel.Forbehavior and Task.Runis consistent

Reference links:


This article will be updated frequently, please read personal blog Original: https://xinyuehtx.github.io/ , in order to avoid misleading the old error of knowledge, and a better reading experience.

Creative Commons License This work is Creative Commons Attribution - NonCommercial - ShareAlike 4.0 International License Agreement for licensing. Welcome to reprint, use, repost, but be sure to keep the article signed by Huang Tengxiao (containing links: https://xinyuehtx.github.io/ ), shall not be used for commercial purposes, be sure to publish the same work based on the paper license modification. If you have any questions, please contact me .

Published 54 original articles · won praise 0 · Views 2441

Guess you like

Origin blog.csdn.net/htxhtx123/article/details/104192341