开发者

Why does a .NET application prevent Windows from shutting down?

开发者 https://www.devze.com 2023-01-12 16:23 出处:网络
One of my applications prevents windows from shutting down if it is running. The only spot where I suspect the cause m开发者_高级运维ay be is FormClosing event handler, which is however quite standar

One of my applications prevents windows from shutting down if it is running.

The only spot where I suspect the cause m开发者_高级运维ay be is FormClosing event handler, which is however quite standard:

EDIT: Removing this handler does not change the situation at all so the cause is somewhere else.

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
}

I have not been able to reproduce this with the simplest possible application containing only this FormClosing handler - the simple application is closed correctly when windows starts shutting down.

What else can prevent windows from shutting down? Where should I look in the code to debug this issue?

I have no custom WndProc implementation in my main form. This is a .NET 2.0 application.

When I run the app in debugger and initiate shutdown, I get only "This program is preventing Windows from shutting down" (Windows 7) for a short while. Windows then shuts down Visual Studio which shuts down the debugger which shuts down the application being debugged.


EDIT: StopAllThreads method

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;
    }
}

Please note: The application can be closed normally when the user closes it manually.


Problem solved: One of the child forms was overriding OnClosing, with the following code:

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


Have you stepped through this code at all to see whether it gets through executing it all or whether it gets stuck somewhere? Possibly the lock cannot get hold of syncLock for some reason and waits.

0

精彩评论

暂无评论...
验证码 换一张
取 消