当winform在c中关闭时,用委托终止新线程
问题描述:
我试图用winform应用程序创建一个新线程。这是我的示例代码。当winform在c中关闭时,用委托终止新线程
public static bool stop = false;
private Thread mythread(){
Thread t = new Thread(delegate() {
while(!stop){
// Something I want to process
}
});
return t;
}
private Button1_click(object sender, EventArgs e){
stop = true; // I know it doesn't work
this.Dispose();
this.Close();
}
public Main(){
InitializeComponent();
Thread thread = mythread();
thread.Start();
}
当按钮1被点击时,新线程和winform应该被终止,但新线程仍然工作。有什么方法可以终止新线程吗?
ps:我试图将我的代码改为MSDN site example,但它只是使它更加复杂。
答
这是在其他线程变量的知名度的问题...试试这个:
private static int stop = 0;
private Thread mythread(){
Thread t = new Thread(delegate() {
while(Thread.VolatileRead(ref stop) == 0){
// Something I want to process
}
});
return t;
}
private Button1_click(object sender, EventArgs e){
Thread.VolatileWrite(ref stop, 1);
this.Dispose();
this.Close();
}
public Main(){
InitializeComponent();
Thread thread = mythread();
thread.Start();
}
注意:不建议
- 中止线程。
- 在你的例子中,停止volatile应该足够了。
- 提供的代码是使用Thread.VolatileRead和Thread.VolatileWrite来更新变量。如果你需要它,使用int而不是bool,而不使用volatile关键字将会简化为Interlocked。
- 我推荐的系列文章Threading in C# by Joseph Albahari
如果在while循环一个漫长的过程,它需要时间来退出。检查每一个命令是否停止更好。您始终可以使用任务来实现此目标。任务有更好的取消机制。 –
你没有正确地做到这一点,线程将永远不会停止的非零赔率。只要这样做是正确的。 –