在我的Windows服务类中:public partial class MyWinSvc: ServiceBase
我有一个只读的Eventlog
属性(ServiceBase
的一部分),该属性在服务启动时包含一个初始化的Eventlog
实例ootb。
出于日志记录的目的,我想使用现有实例,但是我想知道是否必须手动处理此Eventlog
属性,还是自动处理它?
因为我没有对此Eventlog
属性进行初始化,所以如何以及由谁来处理它?
AFAICS它不会在任何地方处置。
Partial class MyWinSvc:
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
仅当您首次访问Eventlog
类的Eventlog属性时才创建此ServiceBase
实例:
ServiceBase
:
public virtual EventLog EventLog
{
get
{
if (this.eventLog == null)
{
this.eventLog = new EventLog()
{
Source = this.ServiceName,
Log = "Application"
};
}
return this.eventLog;
}
}
访问Eventlog属性后,开发人员有责任处置它。
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
if (_eventLogInitialized) // local bool field
{
this.EventLog.Dispose(); // <--
}
base.Dispose(disposing);
}
仅在访问事件日志时才将字段_eventLogInitialized
设置为true。