2014-11-04 73 views
0

以下是我的代码: 将静态log = null的Dispose方法导致内存泄漏吗?如果是,如何避免这一点,并释放静电日志资源?..设置其值= null时,是否会释放静态变量?

public class LogUtil:IDisposable 
{ 
    private StreamWriter logwriter; 
    private LogUtil(StreamWriter sw) 
    { 
     this.logwriter = sw; 
    } 


public void Dispose() 
     { 
      if (log != null) 
      { 
       this.logwriter.Close(); 
       this.logwriter.Dispose();    
       log = null; 
      } 
     } 

    private static LogUtil log = null; 
public static LogUtil getTodayLog() 
{ 
    if (log == null) 
    { 
     String logfilePath = System.Environment.CurrentDirectory + String.Format("\\{0}{1}{2}.log", DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day); 
     StreamWriter sw = new StreamWriter(logfilePath, true, Encoding.UTF8); 
     log = new LogUtil(sw); 
     return log; 
    } 
    else 
     return log; 
} 
} 

回答

3

没有,也不会造成内存泄漏,只要Dispose被调用。

我不知道为什么它首先是静态的。不能log是一个非静态类成员或不被设置为null?在实例销毁时丢弃static并不合乎情理。

在我看来,这个static登录助手可能一直活到应用程序结束。

相关问题