Question on events and local variables
-
Hello, In a button click method I create an EventLog, set its EnableRaisingEvents property to true and attach an event handler for the EntryWritten event.
EventLog eventLog = new EventLog(cbEventLogs.Text,txtMachineName.Text); if(this.txtMachineName.Text == SystemInformation.ComputerName) { eventLog.EnableRaisingEvents = true; eventLog.EntryWritten += new EntryWrittenEventHandler(eventLog_EntryWritten); }
My question is, how does the event still get fired when you exit the button click method where the event log was created? Doesn't the EventLog variable fall out of scope when the method exits, causing it to be garbage collected? Thanx for the help, -Flack -
Hello, In a button click method I create an EventLog, set its EnableRaisingEvents property to true and attach an event handler for the EntryWritten event.
EventLog eventLog = new EventLog(cbEventLogs.Text,txtMachineName.Text); if(this.txtMachineName.Text == SystemInformation.ComputerName) { eventLog.EnableRaisingEvents = true; eventLog.EntryWritten += new EntryWrittenEventHandler(eventLog_EntryWritten); }
My question is, how does the event still get fired when you exit the button click method where the event log was created? Doesn't the EventLog variable fall out of scope when the method exits, causing it to be garbage collected? Thanx for the help, -FlackThe garbage collector will only collect when there reference count goes down to 0. By subscribing eventLog_EntryWritten to the EntryWritten event you are creating a reference. That reference is enough to keep the eventLog alive. Even though you no longer hold a reference one does exist. To get the garbage collector to collect the EventLog unsubscribe the event before eventLog goes out of scope and you no longer have control of any of the references to it. Karl Baum CEO of KGB Technologies Specializing in custom software development.