I have a thread started and I want the user to be able to interrupt it by clicking a button on the form. I found the following code and it demonstrates what I want nicely.
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)
{
}
}
}
I have added the btnStop method. What code needs to be added to stop the thread_clock thread.
Thanks.
First, the thread needs to be able to recognize that it should end. Change
to
And then set endRequested to True in your button click handler.
Note that for this specific case, it is probably more appropriate to use a Timer
http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx
Simply start and stop the timer as desired. You would update the clock from the timer’s Tick() event.