实现IDispose接口
开始想用单体, 后来发现单体还不能满足需求, 就改成个四不像了...
目的就是, 使用Logger时, 显示用TraceLogger.OpenLogger()方法, 使静态成员获取文本路径, 用完后使用Logger.Close()方法销毁这个对象;
也就是在程序执行过程中, 某任务会执行多次, 每次执行的时候都会用一个新的实例去执行, 在整个任务执行过程中只用这一个对象记录日志;
当另外一个任务开始时候, 会新启动另一个实例, 在该任务中只用这一个实例对象记录日志;
这需求, 用实例方法就可以实现, 但是静态方法用起来方便, 于是边写边改就成了这个东西
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ETLUtilityBLL.Enums; using System.Configuration; using ETLUtilityDAL.Common; namespace ETLUtilityBLL { public class TraceLogger : IDisposable { private string _logFilePath; private static TraceLogger LogPath; private TraceLogger() { this._logFilePath = string.Format("{0}\\{1}.txt", ConfigurationManager.AppSettings["LogFilePath"], DateTime.Now.ToString("yyyy_MM_dd_HH_mm")); } static TraceLogger() { LogPath = new TraceLogger(); } public static TraceLogger OpenLogger() { return LogPath; } public static void CloseLogger() { LogPath.Close(); } public static void AppendTraceInfo(TraceLocationType location, TraceType type, string info) { switch (location) { case TraceLocationType.All: break; case TraceLocationType.Database: break; case TraceLocationType.File: AppendInfoToFile(type, info); break; default: throw new ArgumentException("Miss arguments of function! ", "location"); } } private static void AppendInfoToFile(TraceType type , string info) { if (LogPath == null) OpenLogger(); string content = string.Format("{0}\t{1}\t{2}\r\n", DateTime.Now.ToShortTimeString(), Enum.GetName(typeof(TraceLocationType), type), info); FileHelper.WriteStringToFile(LogPath._logFilePath, true, content); } private static void AppendInfotoDB(string info) { throw new NotImplementedException("Method is not implemented! "); } #region IDisposable 成员 private bool disposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { // 清理托管资源 if (!string.IsNullOrEmpty(_logFilePath)) _logFilePath = null; } // 清理非托管资源 if (LogPath != null) { LogPath = null; } //让类型知道自己已经被释放 disposed = true; } //兼容C++的习惯 public void Close() { Dispose(); } /// <summary> /// Destructor, 析构函数 /// </summary> ~TraceLogger() { LogPath = null; //静态成员GC Dispose(false); } #endregion } }
有待验证....