在c#中关闭winform时,使用委托终止新线程

时间:2016-10-11 04:06:26

标签: c# .net multithreading winforms

我尝试使用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 site example,但这只会让它变得更复杂。

1 个答案:

答案 0 :(得分:0)

这是其他线程中变量可见性的问题...试试这个:

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();
}

注意: