我启动了一个线程,我希望用户能够通过单击表单上的按钮来中断它。我找到了以下代码,它很好地展示了我想要的东西。
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
namespace ExThread {
public partial class MainForm : Form {
public int clock_seconds=0;
[STAThread]
public static void Main(string[] args) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
public MainForm() {
InitializeComponent();
Thread thread_clock = new Thread(new ThreadStart(Thread_Clock));
thread_clock.IsBackground = true;
thread_clock.Start();
}
delegate void StringParameterDelegate (string value);
public void Update_Label_Seconds(string value) {
if (InvokeRequired) {
BeginInvoke(new StringParameterDelegate(Update_Label_Seconds), new object[]{value});
return;
}
label_seconds.Text= value + " seconds";
}
void Thread_Clock() {
while(true) {
clock_seconds +=1;
Update_Label_Seconds(clock_seconds.ToString());
Thread.Sleep(1000);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
}
}
}
我添加了 btnStop 方法。需要添加什么代码来停止thread_clock线程。
谢谢。