| 小例子 助你理解 
 [C#] 纯文本查看 复制代码         private static Task t1;
        private static CancellationTokenSource tokenSourceT1;
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            tokenSourceT1 = new CancellationTokenSource();
            var token1 = tokenSourceT1.Token;
            t1 = Task.Factory.StartNew(() =>
            {
                try
                {
                    for (int i = 0; i < 10000000000; i++)
                    {
                        if (token1.IsCancellationRequested)
                        {
                            Invoke(new Action(() =>
                            {
                                label10.Text = "已停止";
                            }));
                            t1.Dispose();
                        }
                        else
                        {
                            Invoke(new Action(() =>
                            {
                                this.listBox2.Items.Add(i.ToString());
                            }));
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(ex.ToString());
                }
            }, token1);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            tokenSourceT1.Cancel();
        } |