In the following program...
using System;
class Program
{
static Parent parent;
static void Main( string[] args )
{
parent = new Parent();
// The program hereafter runs for a long time and occasionally
// causes parent.SomeEvent to be raised.
}
}
class Parent
{
public event EventHandler SomeEvent;
public Parent()
{
new Handler( this );
}
}
class Handler
{
public Handler( Parent parent )
{
parent.SomeEvent += parent_SomeEvent;
}
void parent_SomeEvent( object sender, EventArgs e )
{
// Does something important here.
}
}
Notice that the instantiated Handler
object is not referenced, although it has subscribed to SomeEvent
. Is it possible that, after the program is running for a while, the garbage collector may decide to eliminate the Handler
instance and its parent_SomeEvent
handler will therefore no longer be called whenever parent.SomeEvent
is raised?
I need this clarification for an app I am writing. There are many Handler
-like objects that are instantiated as shown above, without being referenced. The central purpose of Handler
is to subscribe to SomeEvent
. There are no useful methods to call on a reference to the Handler
instance, so I would be fine not referencing it otherwise. I haven't encountered any problems while debugging. But now I am concerned that issues may arise after deployment when the app is running for long periods of time and the garbage collector is more active.