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

Terminate C# application properly and release all resources

我正在开发一个书籍下载应用程序,它工作正常,但是如果在下载完成之前单击 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:它确实在 terminatingmain thread killed 之前显示 message box,但我猜其他一些 thread 在后台保持活动状态

编辑

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

中发生异常

这就是调用所有这些的地方。

client.DownloadProgressChanged += client_DownloadProgressChanged;

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

我正在使用 VS 13 Pro

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

编辑

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

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