The reference page for Application.ThreadException says
Because this is a static event, you must detach your event handlers when your application is disposed, or memory leaks will result.
Notwithstanding the fact that the sample code on that very page does not detach the event handler, does it really leak if the event handler is not detached?
It seems the only time the handler should be detached is if the application shuts down. In that case, whether or not the handler is detached, all the memory used by the application will be freed anyway?
Memory leak occurs when programmers create a memory in heap and forget to delete it. The consequences of memory leak is that it reduces the performance of the computer by reducing the amount of available memory.
Memory leaks can occur in any application written in any language. Sure, older or "near to the metal" languages like C or C++ have more of them. However, it only takes one visit to a badly optimized web page to realize that even a language like JavaScript can suffer from memory leaks.
Use reference objects to avoid memory leaks Using the java. lang. ref package, you can work with the garbage collector in your program. This allows you to avoid directly referencing objects and use special reference objects that the garbage collector easily clears.
A memory leak reduces the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated and all or part of the system or device stops working correctly, the application fails, or the system slows down vastly due to thrashing.
It is probably very uncommon, but a WinForms application's Main()
method could possibly, for some reason, look like this:
static bool AbortStartup { get; set; }
[STAThread]
public static void Main()
{
Application.Run(new CancelableSplashScreen());
if (!AbortStartup)
Application.Run(new MainWindow());
}
When the splash screen closes, the main window will appear, unless the splash screen set the AbortStatup
property to true
. If you added an event handler to Application.ThreadException
from within the splash screen, the instance of CancelableSplashScreen
won't be garbage collected until the application terminates, which may be a considerable time later.
If you let the reference to the object go (assuming it's an instance method that is the event handler) then yes, there will be a leak; you won't be able to unsubscribe from the event (since you don't have the instance anymore) and the object will exist until the app domain ends (as that is the lifetime of static variables).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With