笔记,别人的程序
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 TaskAdvanceDemo
{
public partial class FrmTask : Form
{
private CancellationTokenSource tokenSource = new CancellationTokenSource();
private ManualResetEvent resetEvent = new ManualResetEvent(true);
public FrmTask()
{
InitializeComponent();
}
//启动线程
private void btnStart_Click(object sender, EventArgs e)
{
Task task = new Task(async () =>
{
while (true)
{
if (!tokenSource.IsCancellationRequested)
{
resetEvent.WaitOne();
//在下面编写你要让线程完成的任务...
Console.WriteLine("任务执行中...");
await Task.Delay(1000);
}
}
}, tokenSource.Token);
task.Start();
}
//暂停
private void btnSuspend_Click(object sender, EventArgs e)
{
resetEvent.Reset();
Console.WriteLine("--------------------------任务暂停----------------------------");
}
//继续
private void btnContinue_Click(object sender, EventArgs e)
{
resetEvent.Set();
Console.WriteLine("--------------------------继续执行----------------------------");
}
//结束线程
private void btnCancel_Click(object sender, EventArgs e)
{
tokenSource.Cancel();
Console.WriteLine("--------------------------线程结束----------------------------");
this.btnStart.Enabled = false;
}
}
}