上位机_C#多线程的取消、继续、停止
public Form1() { InitializeComponent(); Task.Run(async () => { for (int i = 0; i < 1000; i++) { if (cancellationToken.IsCancellationRequested) return; manual.WaitOne(); this.Invoke(new Action(() => { textBox1.Text += i.ToString(); })); await Task.Delay(1000); } }, cancellationToken.Token); } CancellationTokenSource cancellationToken = new CancellationTokenSource(); ManualResetEvent manual = new ManualResetEvent(true); private void Form1_Load(object sender, EventArgs e) { cancellationToken.Token.Register(() => { MessageBox.Show("任务已停止"); }); } private void button1_Click(object sender, EventArgs e) { manual.Reset(); } private void button2_Click(object sender, EventArgs e) { manual.Set(); } private void button4_Click(object sender, EventArgs e) { cancellationToken.Cancel(); }