新建一个工程
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 WindowsFormsApp2
{
public partial class Form1 : Form
{
//异步任务发送取消信号,从而安全地终止任务的执行
private CancellationTokenSource cts = new CancellationTokenSource();
//手动停止事件对象
private ManualResetEvent mResetEvent = new ManualResetEvent(true);
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls=false;
}
private void button1_Click(object sender, EventArgs e)
{
//启动
//暂停之后需要再次启动执行
if (cts.IsCancellationRequested)
{
cts = new CancellationTokenSource();
}
Task task = new Task(() => {
int count = 0;
while (!cts.IsCancellationRequested)
{
//用来控制是否需要继续和暂停
mResetEvent.WaitOne();
count++;
listBox1.Items.Add(count.ToString());
Thread.Sleep(1000);
}
}, cts.Token);
task.Start();
}
private void button2_Click(object sender, EventArgs e)
{
// 暂停
mResetEvent.Reset();
}
private void button3_Click(object sender, EventArgs e)
{
//继续
mResetEvent.Set();
}
private void button4_Click(object sender, EventArgs e)
{
//取消
cts.Cancel();
}
}
}