C#.Rihter.Task

task allows get result

        static void Main(string[] args)
        {
            Task<int> t = new Task<int>(n => Sum((int) n), 10000);
            t.Start();
            t.Wait();
            Console.WriteLine("The sum is " + t.Result);
        }

        private static Int32 Sum(Int32 n)
        {
            Int32 sum = 0;
            for (; n > 0; n--)
            {
                checked
                {
                    sum += n;
                }
            }

            return sum;
        }

this is the way how we can cancel and handle the exception

        static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Task<int> t = new Task<int>(n => Sum((int) n, cts.Token), 10000);
            t.Start();
            cts.Cancel();
            try
            {
                Console.WriteLine("The sum is " + t.Result);
            }
            catch (AggregateException e)
            {
                e.Handle(x => x is OperationCanceledException);

                Console.WriteLine("Sum was canceled");
            }
        }

        private static Int32 Sum(Int32 n, CancellationToken ct)
        {
            Int32 sum = 0;
            for (; n > 0; n--)
            {
                ct.ThrowIfCancellationRequested();
                checked
                {
                    sum += n;
                }
            }

            return sum;
        }
This entry was posted in Без рубрики. Bookmark the permalink.