Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application.Exit() which operation is first

Tags:

c#

.net

winforms

When I read the docs on MSDN for Application.Exit(), it says:

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.

In my understanding, to inform all message pump to terminate, this method would finally post a WM_QUIT message to the application message queue. And after posted the message, the method then would close each window(by MSDN). The problem is arising here, when this method try to close each window, the WM_QUIT message should have not been processed, but the MSDN said "it closes all windows after the messages have been processed".

It seems the documentation is contradictory to my inference. What is the problem here, any help is greatly appreciated.

like image 666
IcyBrk Avatar asked Jul 18 '12 21:07

IcyBrk


People also ask

What does application exit do?

The Exit method stops all running message loops on all threads and closes all windows of the application. This method does not necessarily force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return.

How do you exit an application in C#?

Exit(exitCode) function is used to terminate an entire application with the exitCode as the exit code in C#. The Environment. Exit() function terminates the entire current application and returns an exit code to the current operating system.

What does environment exit do?

Exit terminates an application immediately, even if other threads are running. If the return statement is called in the application entry point, it causes an application to terminate only after all foreground threads have terminated.

Which of the following method is used to close the windows form application?

The close() method closes a window.


1 Answers

Interesting question; using ILSpy, let's have a look at what Application.Exit() does:

We see that the critical method is ExitInternal

private static bool ExitInternal()
{
    bool flag = false;
    lock (Application.internalSyncObject)
    {
        if (Application.exiting)
        {
            return false;
        }
        Application.exiting = true;
        try
        {
            if (Application.forms != null)
            {
                foreach (Form form in Application.OpenFormsInternal)
                {
                    if (form.RaiseFormClosingOnAppExit())
                    {
                        flag = true;
                        break;
                    }
                }
            }
            if (!flag)
            {
                if (Application.forms != null)
                {
                    while (Application.OpenFormsInternal.Count > 0)
                    {
                        Application.OpenFormsInternal[0].RaiseFormClosedOnAppExit();
                    }
                }
                Application.ThreadContext.ExitApplication();
            }
        }
        finally
        {
            Application.exiting = false;
        }
    }
    return flag;
}

If everything goes well, the application will first close all forms, then close any forms it missed, and then, finally, it calls Application.ThreadContext.ExitApplication();

As part of ExitApplication, we see the cleanup:

private static void ExitCommon(bool disposing)
{
    lock (Application.ThreadContext.tcInternalSyncObject)
    {
        if (Application.ThreadContext.contextHash != null)
        {
            Application.ThreadContext[] array = new Application.ThreadContext[Application.ThreadContext.contextHash.Values.Count];
            Application.ThreadContext.contextHash.Values.CopyTo(array, 0);
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i].ApplicationContext != null)
                {
                    array[i].ApplicationContext.ExitThread();
                }
                else
                {
                    array[i].Dispose(disposing);
                }
            }
        }
    }
}

// System.Windows.Forms.ApplicationContext
/// <summary>Terminates the message loop of the thread.</summary>
/// <filterpriority>1</filterpriority>
public void ExitThread()
{
    this.ExitThreadCore();
}

What does ExitThreadCore do?

Well, it doesn't directly kill the thread, but it does start the process:

ExitThread and ExitThreadCore do not actually cause the thread to terminate. These methods raise the ThreadExit event to which the Application object listens. The Application object then terminates the thread.

However, the really interesting bit seems to happen in array[i].Dispose(disposing)

As part of this method, we see:

if (this.messageLoopCount > 0 && postQuit)
{
    this.PostQuit();
}

PostQuit() is what sends the WM_QUIT message. So we should also consider when Application.ThreadContext.Dispose is called, and it is always seems to be after the forms have closed, although I'm happy to be corrected there.

So the order seems to be close all forms, then send the WM_QUIT message. I think you are right, the documentation may actually have the events in the wrong order...

It also confirms another side effect we often see; when an application is closed but there is still a thread running in the background, the exe will still be in the list of running applications. The forms have been closed, but there is still that rogue thread, humming along preventing the Exit() from completing.

As Tergiver mentions:

A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.

(from Thread.IsBackgroundThread)

I also wondered what Environment.Exit does:

[SecurityCritical, SuppressUnmanagedCodeSecurity]
[DllImport("QCall", CharSet = CharSet.Unicode)]
internal static extern void _Exit(int exitCode);

It effectively calls out to the OS to kill the process; this will terminate all windows with little grace; the OnFormClosing will probably never get to fire for example. As part of this wholesale termination, it will also [I hesitate to use attempt as I've never seen it fail] kill any threads including the 'main' thread the message loop is running on.

like image 102
dash Avatar answered Sep 30 '22 09:09

dash