2016-09-28 79 views
0

當我在一個漫長的過程中使用被調用的等待窗體的線程時,出現了錯誤。錯誤:線程在c#Windows應用程序中被中止

「的類型 'System.Threading.ThreadAbortException' 未處理的異常出現在 System.Windows.Forms.dll中

其他信息:線程已被中止。」

有時我的代碼運行良好,但有時會出現此錯誤。

class ProgressCLS 
{ 
    private static Thread th = new Thread(new ThreadStart(showProgressForm)); 
    public void startProgress() 
    { 
     th = new Thread(new ThreadStart(showProgressForm)); 

     th.Start(); 
    } 

    private static void showProgressForm() 
    {    
       Waiting sForm = new Waiting();    
       sForm.ShowDialog(); 
    } 

    public void stopProgress() 
    { 
      th.Abort(); 
      th = null;   
    } 


} 

我得到了showProgressForm()方法這個錯誤在sform.ShowDialog()

,我叫這個類的主要程序是這樣的:

ProgressCLS PC = new ProgressCLS(); 
PC.startProgress(); 
TodayDate = txtDate.SelectedDateTime.ToString("yy-MM-dd"); 
ClearField(); 
CalculateMSG(); 
tabControl1.SelectedIndex = 1; 
btnShowFolderLocal.Enabled = true; 
btnShowFolderTop.Enabled = true; 
btnShowDpsFailed.Enabled = true; 
btnShowDpsFailed2.Enabled = true; 
btnShowFolderTopic.Enabled = true; 
ShowMSGButtonClicked = true; 
PC.stopProgress(); 

什麼想法?

+0

這是因爲你使用了Thread.Abort(),並且你有一個try/catch-em-all語句,你沒有發佈。不要捕獲ThreadAbortException。 –

+0

您不需要單獨的線程來顯示進度表單。用'Show'而不是'ShowDialog'顯示*非模態*形式。如果要報告其他任務/線程的進度,請使用「進度」並訂閱其事件 –

+0

[C#窗體控件不會使用多線程更新]的可能重複(http://stackoverflow.com/questions/38588884/ c-sharp-form-controls-wont-update-with-multithreading) –

回答

1
private static Thread th = new Thread(new ThreadStart(showProgressForm)); 
public void startProgress() 
{ 
    th = new Thread(new ThreadStart(showProgressForm)); 
    th.Start(); 
} 

不是什麼大不了的,但爲什麼你實例化你的線程兩次?不是很乾淨。 我認爲只有你的ctor中的一個是強制性的,因爲你在調用stopProgress()時設置了th = null。

反正看你的代碼,並記住線程是異步的,因此:

 ProgressCLS PC = new ProgressCLS(); 
     PC.startProgress(); 

它運行在一個專用線程的進度表(異步的,所以你的代碼仍然在運行)。

TodayDate = txtDate.SelectedDateTime.ToString("yy-MM-dd"); 
    ClearField(); 
    CalculateMSG(); 
    ... 

你在主線程中執行過程的系列(synchrounously,你的進步仍形式在後臺運行)。

 PC.stopProgress(); 

無論進度表的狀態如何,它都會中止。正如你可能錯過了MSDN documentation,它「在調用它的線程中引發一個ThreadAbortException」。因此,公平地說,你的代碼「有時候工作」甚至是奇怪的,因爲如果它碰到th.Abort()行,它應該失敗。

這裏有幾個提示:

  • 我們通常運行在主線程UI形式,並在後臺處理
  • 以您目前的設計中,你可能會遇到麻煩,如果你們中的任何處理(克利爾()和CalculateMSG())具有異步操作。
  • 您很少需要明確地中止一個線程(只有在出現意外錯誤時)。當進展完成時,只需關閉表格,Gargbage Collector就可以完成剩下的工作。
+0

你是對的。但我做到了,但沒有工作 –

+0

答案更新更清晰。 – Ouarzy

+0

@MajidQafouri你爲什麼使用單獨的線程?當我使用show()而不是showDialog()時,只需調用'Show()'而不是ShowDialog()' –