当c#中winform关闭时,用委托终止新线程
本文关键字:新线程 终止 线程 winform | 更新日期: 2023-09-27 18:12:34
我尝试使用winform应用程序创建一个新线程。下面是我的示例代码。
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();
}
单击button1时,应该终止新线程和winform,但新线程仍在工作。有什么方法可以终止新线程吗?
ps:我试图改变我的代码参考MSDN网站的例子,但它只会使它更复杂。
这是一个变量在其他线程可见性的问题…试试这个:
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();
}
指出:
- 不建议终止线程。
- 在你的例子中,设置stop为volatile应该足够了。
- 当前代码正在使用线程。VolatileRead和Thread。用VolatileWrite来更新变量。如果需要的话,使用int而不是bool,并且不使用volatile关键字可以轻松转换到Interlocked。我推荐Joseph Albahari的c#线程系列文章