【问题标题】:Why does a .NET application prevent Windows from shutting down?为什么 .NET 应用程序会阻止 Windows 关闭?
【发布时间】:2011-04-03 01:18:00
【问题描述】:

我的一个应用程序会阻止正在运行的窗口关闭。

我怀疑原因的唯一地方是 FormClosing 事件处理程序,但它是相当标准的:

编辑:删除此处理程序根本不会改变情况,因此原因在其他地方。

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason != CloseReason.UserClosing)
    {
        StopAllThreads(); 
        //let close
        return;
    }
    //ask user whether he wants to save his work
}

我无法使用仅包含此 FormClosing 处理程序的最简单的应用程序来重现这一点 - 当窗口开始关闭时,简单的应用程序会正确关闭。

还有什么可以防止 Windows 关闭?我应该在哪里查看代码以调试此问题?

我的主窗体中没有自定义 WndProc 实现。这是一个 .NET 2.0 应用程序。

当我在调试器中运行应用程序并启动关闭时,我只得到“此程序正在阻止 Windows 关闭”(Windows 7)一小段时间。然后,Windows 会关闭 Visual Studio,后者会关闭调试器,而调试器会关闭正在调试的应用程序。


编辑:StopAllThreads 方法

public static void StopAllThreads()
{
    lock (syncLock)
    {
        foreach (IStop stoppable in stoppables)
        {
            try
            {
                stoppable.Stop(); //stops a running thread by setting a volatile boolean flag
            }
            catch (Exception ex)
            {
                Debug.Fail("Error stopping a stoppable instance: " + ex.ToString());
            }
        }
        stoppables.Clear();
        disposed = true;
    }
}

请注意:应用程序在用户手动关闭时可以正常关闭。

【问题讨论】:

  • StopAllThreads 的代码是什么样的?
  • 我看到你正在使用线程(或者至少,我假设你是);你能不能有一些没有被关闭的后台线程?
  • 删除此功能后会发生什么?
  • 我看到您的评论“要求用户保存他的工作”。是否出现了阻止关机的模式窗口?
  • @silky:我已经编辑了问题

标签: .net windows debugging shutdown


【解决方案1】:

你有没有仔细检查过这段代码,看看它是否能全部执行完,或者它是否卡在某个地方?可能由于某种原因锁无法获取syncLock并等待。

【讨论】:

    【解决方案2】:

    问题已解决:其中一个子表单覆盖了OnClosing,代码如下:

        protected override void OnClosing(CancelEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }
    

    【讨论】:

    • 为了解决这个问题,在我的例子中,我添加了条件:if (e.CloseReason == CloseReason.UserClosing) e.Cancel = true;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 2013-04-13
    • 2016-06-19
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多