2016-10-11 47 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(); 
} 

注意:不建議

相關問題