我正在开发一本书下载应用程序,它工作正常,但如果在下载完成之前点击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线程上调用最后两行。这是否在后台工作人员中运行?什么叫这种方法来更新下载?在调试器中运行并在第二次关闭后按“暂停”时,它会突出显示哪一行? –