PRB: Call to ExitProcess() from Visual Basic Application Hinders Process Exit

Symptoms

If a Visual Basic application makes a direct call to the ExitProcess() API, the process may not properly exit. In some instances, a call to ExitProcess() will even cause an access violation or cause the process to deadlock.

Calling ExitProcess() from a Visual Basic application is unsupported.

Cause

The ExitProcess() API should not be called by a thread when other threads still need to clean up their own resources. If there are other running threads that have not exited, the ExitProcess() routine will abruptly terminate them. This can cause data loss and other unpredictable behavior.

The Visual Basic run-time engine is responsible for the execution of a Visual Basic application. Not only does this engine interpret and execute the code within the application, but it also initializes and cleans up the process. Because the Visual Basic run-time engine allocates resources, only it can know when the resources are released. Thus, only the run-time engine can safely call ExitProcess().

Resolution

The proper way to exit a Visual Basic application is to naturally exit Sub Main or unload the form specified as the "Startup Object" within the application's Project Properties.

More Information

One particular instance in which a call to ExitProcess() is known to cause a problem involves COM objects. If a Visual Basic application has an outstanding reference to an out-of-process COM object when it calls ExitProcess(), the calling process is likely to "hang" or cause an access violation. A direct call to CoUninitialize() immediately before the call to ExitProcess() will usually prevent this problem. Although this approach allows you to work around the problem, it is not recommended or supported by Microsoft.

The only advantage that would arise out of calling ExitProcess() from a Visual Basic application is the ability to set an exit code for the process. But because of the unpredictable nature of calling ExitProcess() from Visual Basic, it is better to communicate the success or failure of the process through some other means, such as writing an exit code to a file or sending a windows message to another process.
Propriedades

ID do Artigo: 288216 - Última Revisão: 14 de jul de 2004 - Revisão: 1

Comentários