c# 简单任务取消

c# Simple TASK Cancel

我正在绑定停止线程,但没有任何效果。 我正在尝试 100 种方法。 怎么了 ? 很烦人

(我必须在这里写一些文字,因为 whosebug.com 不允许我发送这个 post)(我必须在这里写一些文字,因为 whosebug.com 不允许请允许我发送此 post)(我必须在这里写一些文字,因为 whosebug.com 不允许我发送此 post)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
        private static CancellationTokenSource cts = new CancellationTokenSource();
        private CancellationToken ct = cts.Token;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() => 
            {
                work_for_task(ct);
            }, this.ct);
        }

        private void work_for_task(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                ct.ThrowIfCancellationRequested();
            }

            for (int i = 0; i < 5; i++)
            {
                if (richTextBox2.InvokeRequired)
                {
                    richTextBox2.Invoke((MethodInvoker)delegate
                    {
                        richTextBox2.AppendText("I AM IN: " + Thread.CurrentThread.Name + "\n");
                    });

                    Thread.Sleep(1400);
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("CANCELED");
            cts.Cancel();
        }
    }
}

只是这个而不是你的 work_for_task 方法:

private void work_for_task(CancellationToken ct)
{
    for (int i = 0; i < 5; i++)
    {
        if (ct.IsCancellationRequested)
        {
            return; 
        }
        if (richTextBox2.InvokeRequired)
        {
            richTextBox2.Invoke((MethodInvoker)delegate
            {
                richTextBox2.AppendText("I AM IN: " + Thread.CurrentThread.Name + "\n");
            });

            Thread.Sleep(1400);
        }
    }
}