2015-11-02 117 views
0

我正在開發一本書下載應用程序,它工作正常,但如果在下載完成之前點擊Exit button,程序將引發exception,我處理exception,但在此之後我按Exit button,程序關閉,但它並沒有完全終止,它繼續執行,除非從Task Manager中死亡。正確終止C#應用程序並釋放所有資源

這是代碼段。

try 
{    

    string placeholder = " KB"; 
    string placeholder1 = " KB"; 
    double bytesIn = double.Parse(e.BytesReceived.ToString()); 
    double totalBytes = double.Parse(e.TotalBytesToReceive.ToString()); 
    // get the elapsed time in milliseconds 
    ctime = stopwatch.ElapsedMilliseconds; 
    // get the received bytes at the particular instant 
    current = e.BytesReceived; 
    // calculate the speed the bytes were downloaded and assign it to a Textlabel (speedLabel in this instance) 
    string speed = ((int)(((current - previous)/(double)1024)/((ctime - ptime)/(double)1000))).ToString() + " KB/s"; 
    previous = current; 
    ptime = ctime; 
    double percentage = bytesIn/totalBytes * 100; 
    bytesIn = Math.Round(bytesIn/1024, 2); 
    if (bytesIn > 2000) 
    { 
     bytesIn = Math.Round(bytesIn/1024, 2); 
     placeholder = " MB"; 
    } 
    totalBytes = Math.Round(totalBytes/1024, 2); 
    if (totalBytes > 2000) 
    { 
     totalBytes = Math.Round(totalBytes/1024, 2); 
     placeholder1 = " MB"; 
    } 
    this.BeginInvoke((MethodInvoker)delegate 
    { 
     labelPercentage.Text = "Downloading " + Convert.ToInt32(percentage) + "% - " + bytesIn + placeholder + "/" + totalBytes + placeholder1 + " @ "+ speed; 
     downloadProgressBar.Value = int.Parse(Math.Truncate(percentage).ToString()); 
    }); 
} 
catch (Exception) 
{ 
    AutoClosingMessageBox.Show("Terminating..", "Closing", 2000); 
    this.Close(); 
    System.Windows.Forms.Application.Exit(); 
} 

PS:它顯示message boxterminatingmain thread killed之前,但我想一些其他的thread背景永葆

編輯只

現在我調用最後兩行,我得到InvalidOperationException,當我不明白的時候,它發生異常invoke

這就是所有被調用的地方。

client.DownloadProgressChanged += client_DownloadProgressChanged; 

當我按下按鈕Exit,程序就會被終止,但它繼續按照VS執行。

我使用VS 13 Pro

+0

可能重複[如何關閉所有正在運行的線程?](http://stackoverflow.com/questions/2688923/how-to-close-all-running-threads) –

+0

@ gabriel:謝謝,但我猜如果這可能是線程問題,那麼它不應該拋出異常。 – Mubin

+2

拋出什麼異常?它扔在哪裏?作爲一個方面說明,你所做的大部分工作不需要在UI線程上調用,只需要在UI線程上調用最後兩行。這是否在後臺工作人員中運行?什麼叫這種方法來更新下載?在調試器中運行並在第二次關閉後按「暫停」時,它會突出顯示哪一行? –

回答

2

根據來源,我假設你正在使用的Web客戶端組件。在退出應用程序之前,您需要取消下載。我只需在包含WebClient的窗口上添加一個client.Dispose()調用到Closed事件處理程序。

編輯

此外,如果這也不行,把Environment.Exit(0);這將終止預期。

+0

我在'退出按鈕單擊事件'上添加了這個'Dispose'客戶端,然後終止應用程序,但仍然是同樣的問題。 – Mubin

0

嘗試使用「使用」關鍵字並將代碼放入「使用」塊中。這應該通過處理所有變量來正確終止您的應用程序。