Wednesday, May 7, 2008

GC in c# is not as stronger as i thought..

relative links:
http://forums.microsoft.com/forums/ShowPost.aspx?PostID=3242882&SiteID=1
http://www.mztools.com/articles/2005/mz2005012.aspx

key problem:
reference to a local variable after exit the region where the variable is defined.

So, I recall the reference count in c++.

////////
//example from http://www.mztools.com/articles/2005/mz2005012.aspx

When using a C# add-in to receive events from Visual Studio .NET, it can happen that after a while the add-in no longer receives them. Consider this code:

private _DTE applicationObject;

public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode,
object addInInst, ref System.Array custom)
{
EnvDTE.SolutionEvents solutionEvents;

applicationObject = (_DTE) application;
solutionEvents = applicationObject.Events.SolutionEvents;
solutionEvents.Opened += new _dispSolutionEvents_OpenedEventHandler(SolutionOpened);
}

private void SolutionOpened()
{
MessageBox.Show("Solution opened");
}
Since the solutionEvents variable is local to the OnConnection procedure, when the procedure exits the variable is no longer used and it will be garbage collected the next time that the garbage collector performs its job. Until that moment you receive events, but after that the event handler is disconnected. To solve this problem, you must declare the solutionEvents variable at class level, not at procedure level:
private _DTE applicationObject;
private EnvDTE.SolutionEvents solutionEvents;
public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode,
object addInInst, ref System.Array custom)
{
applicationObject = (_DTE) application;
solutionEvents = applicationObject.Events.SolutionEvents;
solutionEvents.Opened += new _dispSolutionEvents_OpenedEventHandler(SolutionOpened);
}

private void SolutionOpened()
{
MessageBox.Show("Solution opened");
}

}

No comments: