正确终止C#应用程序并释放所有资源

时间:2015-11-02 02:45:56

标签: c# winforms exception-handling

我正在处理图书下载应用程序,它工作正常,但如果在下载完成之前点击Exit button,程序会抛出exception,我处理exception但是之后,当我按Exit button时,程序将关闭,但它不会完全终止,除非被Task Manager杀死,否则它将继续执行。

这是片段。

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 boxterminating之前显示main thread killed,但我猜其他thread在后​​台保持活着

修改

现在我只调用最后两行,当我没有捕获它时,我得到InvalidOperationException,并且在invoke

中发生异常

这就是所有这一切的所在。

client.DownloadProgressChanged += client_DownloadProgressChanged;

当我按下Exit按钮时,程序会终止,但会继续根据VS执行。

我正在使用VS 13 Pro

2 个答案:

答案 0 :(得分:2)

根据消息来源,我假设您正在使用WebClient组件。退出应用程序之前,您需要取消下载。我只想在包含WebClient的窗口上向Closed事件处理程序添加client.Dispose()调用。

修改

此外,如果这不起作用,请放置Environment.Exit(0);,这将按预期终止。

答案 1 :(得分:0)

尝试使用"使用"关键字并将您的代码放入'使用'块。这应该像你期望的那样通过处理所有变量来正确终止你的应用程序。