namespace 线程的开启与暂停
{
public partial class Form1 : Form
{
/// <summary>
/// 线程暂停控制,默认开启
/// </summary>
private ManualResetEvent manual = new ManualResetEvent(true);
/// 线程启停控制
private CancellationTokenSource cts;
private int CurrentValue = 0;
public Form1()
{
InitializeComponent();
}
//线程方法
private void TaskMethod()
{
while (!cts.IsCancellationRequested)
{
manual.WaitOne();
CurrentValue++;
if (CurrentValue == 200)
{
CurrentValue = 0;
}
try
{
this.Invoke(new Action(() => {
this.label1.Text = "当前值:" + CurrentValue;
}));
}
catch (Exception ex)
{
}
Thread.Sleep(100);
}
}
//线程开启
private void button1_Click(object sender, EventArgs e)
{
cts = new CancellationTokenSource();
Task.Run(() =>
{
TaskMethod();
}, cts.Token);
}
//线程停止
private void button2_Click(object sender, EventArgs e)
{
cts.Cancel();
CurrentValue = 0;
}
//线程暂停
private void button3_Click(object sender, EventArgs e)
{
manual.Reset();
}
//线程继续
private void button4_Click(object sender, EventArgs e)
{
manual.Set();
}
}
}