Demo entry 6660207

dsadasd

   

Submitted by anonymous on Nov 14, 2017 at 14:25
Language: C#. Code size: 1.7 kB.

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {
            CancellationTokenSource ctSource = new CancellationTokenSource();
            CancellationToken ctToken = ctSource.Token;

            Task t1 = DoAsync(ctSource, ctToken);
            t1.Wait();
        }

        private static async Task DoAsync(CancellationTokenSource ctSource, CancellationToken ctoken)
        {
            if (ctoken.IsCancellationRequested)
                return;

            var taskCount = Task.Run(() => Count(ctoken), ctoken);
            var taskStop = Task.Run(() => Stop(ctSource), ctoken);
            var taskArray = new[] { taskCount, taskStop };

            await Task.WhenAll(taskArray);
        }

        public static void Count(CancellationToken ctoken)
        {
            for (int i = 0; i < 100; i++)
            {
                if (ctoken.IsCancellationRequested)
                {
                    Console.WriteLine("stopped at :" + i);

                    break;
                }
                else
                {
                    Console.WriteLine(i);
                    Thread.Sleep(150);
                }
            }
        }

        public static void Stop(CancellationTokenSource cSource)
        {
            Random r = new Random();
            int milliseconds = r.Next(1000, 6000);
            Console.WriteLine("In" + milliseconds + "  milliseconds: " + "count will stop...");

            Thread.Sleep(milliseconds);
            cSource.Cancel();
        }

    }
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).