说明:
通过使用System.Threading命名空间下的
CancellationTokenSource类的
.Token.IsCancellationRequested和.Cancel()来结束线程
控件布局
代码
using System;
using System.Threading;//CancellationTokenSource类用到
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
public static CancellationTokenSource cts;
private void button1_Click(object sender, EventArgs e)
{
cts = new CancellationTokenSource();
Thread t = new Thread(() =>
{
while (true)
{
if (cts.Token.IsCancellationRequested)//获取到取消请求
{
textBox1.Text += "线程被终止!\r\n";
break;
}
textBox1.Text += DateTime.Now.ToString() + "\r\n";
Thread.Sleep(100);
}
});
t.Start();
}
private void button2_Click(object sender, EventArgs e)
{
cts.Cancel();//执行取消,使cts.Token.IsCancellationRequested为true
}
}
}