Reputation: 896
I have a windows application in which I load a lot of data in memory (I know loading that much data into memory is not a good option, but I don't have a choice).
There are some situations where I quit my application using the Application.Exit()
method.
I am bit confused with the process of freeing the memory the application was holding. I.e. when I call Application.Exit()
, will this internally call GC.Collect()
, or would it be better if I first call GC.Collect()
myself, and Application.Exit()
afterwards?
How does Application.Exit()
work internally?
I tried to find the answer by googling, but did not find what I am looking for.
Upvotes: 2
Views: 3646
Reputation: 22133
Once a process terminates, all the resources that belonged to it are freed. This is performed by the operating system; there is no chance of a leak once a process is killed.
The garbage collector is responsible for managing memory allocation during the lifetime of the process; it has no influence on what happens to these resources once the process exits.
That said, Application.Exit() does not force a process to terminate; it merely closes all application windows. Whether that terminates the process or not depends on what the process was doing. To force a process to exit, call Environment.Exit().
Upvotes: 2
Reputation: 754883
I believe your main problem here is you are confusing global resources with process resources. The garbage collector is responsible for managing memory within a process. It is a process resource and has no effect on the memory available to other processes in the system. Whether or not the GC runs before exit is uninteresting to other processes on the system
Upvotes: 4
Reputation: 216323
One benefit to use a framework like NET is not to worry about these details.
Of course you need to try to keep your memory usage low as possible, but the workload to free the MANAGED memory used by your application is a job reserved to the framework that will not stop to clean the memory references just because your application is terminated by Application.Exit()
As for the code of Application.Exit() it is easy to find on internet
private static bool ExitInternal()
{
bool flag = false;
lock (internalSyncObject)
{
if (exiting)
{
return false;
}
exiting = true;
try
{
if (forms != null)
{
foreach (Form form in OpenFormsInternal)
{
if (form.RaiseFormClosingOnAppExit())
{
flag = true;
break;
}
}
}
if (!flag)
{
if (forms != null)
{
while (OpenFormsInternal.Count > 0)
{
OpenFormsInternal[0].RaiseFormClosedOnAppExit();
}
}
ThreadContext.ExitApplication();
}
return flag;
}
finally
{
exiting = false;
}
}
return flag;
}
Upvotes: 1