2015-11-02 116 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

尝试使用“使用”关键字并将代码放入“使用”块中。这应该通过处理所有变量来正确终止您的应用程序。