Reputation: 1930
I've been trying to identify some performance issues with our ASP.NET Web application. It's an online application, used by multiple users(10+). Just a quick overview: The applcation uses a combination of web forms, MVC Pages, web services etc... When multiple users connects to the app, it seems to become really slow. After investigating the memory, it seems as if the application is using A LOT of memory and that is slowing down the machine, which indicates unmanaged resources not being disposed of. I installed ANTS, and then captured a few applications on the system. It turns out a lot of the memory is used by unmanaged resources: http://tinypic.com/r/154ujra/7
This is the first time I've been profiling memory. ANTS profiler indicates that one of my classes (RULE) has a high number of live instances: http://tinypic.com/r/1264ltu/7 (Which doesn't seem to be freed up by the GC)
After drilling down into class level, http://tinypic.com/r/2r3v6nq/7, it displays a warning that the class isn't released from memory, and this could be because of an event handler not being unregistered. Now that class does contain an event handler instance, so could it be that?
public class Rule
{
public event EventHandler deleted;
public void Delete()
{
if (baseQuestionnaire.basePortfolio.mode != Mode.Admin)
{
throw new Exception("Rules can only be deleted in Admin mode");
}
else
{
// Delete the rule from the database
if (id != -1)
{
string delete = "DELETE FROM tb" + DataManager.dbPrefix + "_QuestionRule WHERE QuestionRuleId = " + id.ToString();
DataManager.execute(delete);
}
// Raise a deleted event
if (deleted != null)
deleted(this, new EventArgs());
}
}
}
Event is then assigned in another class like this, but never unregistered
public class Option : IComparable
{
public void AddRule(Rule newRule)
{
newRule.deleted += new EventHandler(newRule_deleted);
allRules.Add(newRule);
}
............................
}
Upvotes: 1
Views: 319
Reputation: 9049
Hmm.. I see that the eventhandler 'deleted' is a public one. So my guess is that the Rule object is created first and then the Rule.deleted is assigned an eventhandler. If this is the case then as you suspected, the eventhandler is probably the cause of Rule objects not being garbage collected.
EDIT:
Maybe you could try something like this:
public class Option : IComparable, IDisposable
{
private Rule newRule;
private EventHandler newRuleDeletedEventHandler;
public void AddRule(Rule newRule)
{
this.newRule = newRule;
newRuleDeletedEventHandler = new EventHandler(newRule_deleted);
newRule.deleted += newRuleDeletedEventHandler;
allRules.Add(newRule);
}
public override void dispose()
{
newRule.deleted -= newRuleDeletedEventHandler;
}
}
Upvotes: 1