スレッドを開始しましたが、ユーザーがフォームのボタンをクリックしてスレッドを中断できるようにしたいと思います。私は次のコードを見つけました、そしてそれは私がうまく欲しいものを示しています。
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スレッドを停止するために追加する必要のあるコード。
ありがとう。