C# 立即取消异步线程
当按下开始按钮时,我启动一个线程,该按钮启动延迟计时器,然后显示消息框对话框。 现在,我试图停止这个线程,但我找不到办法,除了添加一个标志,该标志将阻止线程显示 messageBox 对话框,但不会杀死该线程。 如果您能建议一种杀死线程的方法,我将不胜感激。
谢谢 莫蒂
public partial class Form1 : Form
{
public delegate void example();
ThreadA threadA = null;
public Form1()
{
InitializeComponent();
}
example ex;
IAsyncResult result;
private void button_Start_Click(object sender, EventArgs e)
{
ex = new example(start);//.BeginInvoke(null, null);
result = ex.BeginInvoke(null, null);
}
private void button_Stop_Click(object sender, EventArgs e)
{
if (threadA != null)
threadA = null;
}
private void start()
{
if (threadA == null)
{
threadA = new ThreadA();
threadA.run();
}
}
}
class ThreadA
{
//public event
public Boolean flag = false;
public void run()
{
Thread.Sleep(15000);
MessageBox.Show("Ended");
}
}
I start a thread when pressing on start button which start a delay timer and then show a messageBox dialog.
Now, I'm trying to stop this thread, but I can't find a way for that, except add a flag which will prevent the thread to display the messageBox dialog but not to kill the thread.
I would appreciate if you can suggest a way to KILL the thread.
Thanks
Moti
public partial class Form1 : Form
{
public delegate void example();
ThreadA threadA = null;
public Form1()
{
InitializeComponent();
}
example ex;
IAsyncResult result;
private void button_Start_Click(object sender, EventArgs e)
{
ex = new example(start);//.BeginInvoke(null, null);
result = ex.BeginInvoke(null, null);
}
private void button_Stop_Click(object sender, EventArgs e)
{
if (threadA != null)
threadA = null;
}
private void start()
{
if (threadA == null)
{
threadA = new ThreadA();
threadA.run();
}
}
}
class ThreadA
{
//public event
public Boolean flag = false;
public void run()
{
Thread.Sleep(15000);
MessageBox.Show("Ended");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将使用带有
CancellationTokenSource
的Task
类。编辑2:对您的评论:
I'd Use the
Task
Class with aCancellationTokenSource
.Edit2: to your Comment:
使用ManualResetEvent
但是,如果线程不会一直工作,我会使用Timer。
Use
ManualResetEvent
However, I would use a
Timer
if the thread is not going to do work all the time.