2016-10-11 101 views
0

我试图用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,但它只是使它更加复杂。

+0

如果在while循环一个漫长的过程,它需要时间来退出。检查每一个命令是否停止更好。您始终可以使用任务来实现此目标。任务有更好的取消机制。 –

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

注意:不建议

相关问题