取消架構

===========================Parallel.For()方法的取消c#

(在1秒鐘以後取消並行循環)架構

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //通知 CancellationToken,告知其應被取消
            CancellationTokenSource cts = new CancellationTokenSource();
            //註冊一個委託,在取消時觸發
            cts.Token.Register(() => Console.WriteLine("取消構架觸發"));
            //新建一個任務,用於在1秒鐘以後取消並行循環
            Task t = new Task(() => {
                Thread.Sleep(1000);
                //傳達取消請求
                cts.Cancel();
            });
            //啓動任務
            t.Start();
 
            try
            {
                //並行循環
                Parallel.For(0, 10, new ParallelOptions() { CancellationToken = cts.Token }, i =>
                {
                    Console.WriteLine(i);
                });
            }
            //調用的塊沒有完成就取消架構,則會拋出OperationCanceledException異常
            catch (OperationCanceledException e)
            {
                Console.WriteLine("拋出OperationCanceledException異常");
            }
 
            Console.ReadKey();
        }
    }
}

 

===========================任務的取消ide

(在1秒鐘以後取消任務)spa

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //通知 CancellationToken,告知其應被取消
            CancellationTokenSource cts = new CancellationTokenSource();
            //註冊一個委託,在取消時觸發
            cts.Token.Register(() => { Console.WriteLine("取消構架觸發"); });
            //新建一個任務,用於在1秒鐘以後取消任務
            Task t = new Task(() => {
                Thread.Sleep(1000);
                cts.Cancel();
            });
            t.Start();

            //任務
            TaskFactory sf = new TaskFactory(cts.Token);
            Task tsf= sf.StartNew(() => {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine(i);
                }
            });
            try
            {
                //等待任務執行完成
                tsf.Wait();
            }
            //調用的塊沒有完成就取消架構,則會拋出AggregateException異常
            catch (AggregateException)
            {
                Console.WriteLine("拋出AggregateException異常");
            }
           
            Console.ReadKey();

        }
    }
}
相關文章
相關標籤/搜索