我正在開發一本書下載應用程序,它工作正常,但如果在下載完成之前點擊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 box
terminating
和main thread killed
之前,但我想一些其他的thread
背景永葆
編輯只
現在我調用最後兩行,我得到InvalidOperationException
,當我不明白的時候,它發生異常invoke
這就是所有被調用的地方。
client.DownloadProgressChanged += client_DownloadProgressChanged;
當我按下按鈕Exit
,程序就會被終止,但它繼續按照VS
執行。
我使用VS 13 Pro
可能重複[如何關閉所有正在運行的線程?](http://stackoverflow.com/questions/2688923/how-to-close-all-running-threads) –
@ gabriel:謝謝,但我猜如果這可能是線程問題,那麼它不應該拋出異常。 – Mubin
拋出什麼異常?它扔在哪裏?作爲一個方面說明,你所做的大部分工作不需要在UI線程上調用,只需要在UI線程上調用最後兩行。這是否在後臺工作人員中運行?什麼叫這種方法來更新下載?在調試器中運行並在第二次關閉後按「暫停」時,它會突出顯示哪一行? –