gpt4 book ai didi

c# - 如何使用 C# 从 UI 终止线程

转载 作者:行者123 更新时间:2023-11-30 13:59:51 26 4
gpt4 key购买 nike

我启动了一个线程,我希望用户能够通过单击表单上的按钮来中断它。我找到了以下代码,它很好地展示了我想要的东西。

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线程。

谢谢。

最佳答案

首先,线程需要能够识别它应该结束。改变

void Thread_Clock() {
while(true) {

bool endRequested = false;
void Thread_Clock() {
while(!endRequested) {

然后在您的按钮点击处理程序中将 endRequested 设置为 True。

private void btnStop_Click(object sender, EventArgs e)
{
endRequested = true;
}

请注意,对于这种特定情况,使用 Timer 可能更合适

http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

只需根据需要启动和停止计时器。您将从计时器的 Tick() 事件更新时钟。

关于c# - 如何使用 C# 从 UI 终止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12556688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com