2011-12-09 138 views
-1
public class Settings 
    { 
     public static readonly string fileName = "config.ini"; 
     private IConfigSource src 
     { 
      get 
      { 
       CreateIfNotExists(); 
       return new IniConfigSource(fileName); 
      } 
     } 

     public void test1() 
     { 
      //var src = new IniConfigSource(fileName); ; 
      src.Configs["DATA"].Set("baa", "haaaaee"); 
      src.Save(); 
     } 

     public void test2() 
     { 
      var src2 = new IniConfigSource(fileName); ; 
      src2.Configs["DATA"].Set("baa", "haaaaee"); 
      src2.Save(); 
     } 

    public Stream CreateIfNotExists() 
    { 
     if (!File.Exists(fileName)) 
     { 
      Stream file = File.Create(fileName); 
      return file; 
     } 

     return null; 
    } 
} 

为什么test2()方法正常工作并且test1()无法正常工作?获得{}不能按预期工作

+0

为什么您在test1中注释了'src'声明? – norlando

+2

会发生什么?有抛出异常吗? –

+0

我们需要更多的代码才能理解。 src的来源以及它与CreateIfNotExists的关系,看起来像是内存泄漏。 –

回答

2

它不起作用,因为您的“src”属性每次调用它时都会创建一个新的IniConfigSource。你的“测试”期望它在通话中是同一个。

将您的IniConfigSource的结果存储在一个私有变量中,并在设置后使用它。

private IConfigSource _src; 
    private IConfigSource src 
    { 
     get 
     { 
      if(_src == null) 
       _src = new IniConfigSource(fileName); 
      return _src; 
     } 
    } 

我不打算进入,为什么CreateIfNotExists有可言,考虑到流返回从不使用并丢弃到GC。

+0

我改了名字,并继续不工作。 –

+0

我没有说改名字。 –

+0

非常感谢! –

0

CreateIfNotExists创建了一个FileStream的实例,并且不处理它。这导致FileStream锁定该文件,并因此随后打开该文件失败。

从第一次测试IniConfigSource的实例可能会保持文件打开,但我不知道,因为你没有发布相关的源代码。

您的懒惰初始化模式也被破坏,在每次访问时返回一个新的IniConfigSource实例。如果你想延迟初始化,为什么不使用Lazy<T>类?


除此之外错误,有副作用的吸气剂是非常不良作风。

另一个(次要)问题是存在检查和调用create之间的竞争条件。如果文件被删除,代码之间失败。

+0

这不是我真正的代码。在实际代码中,我关闭文件流 –

+0

@TheMask然后发布真实代码或至少代表它的一个代表性子集。您需要在下次打开文件之前进行处理,因此第一次测试可能会阻止第二次测试。 – CodesInChaos

1

srctest1test2IniConfigSource两个不同的实例(不再适用于有你的编辑)。

test1失败的原因是每一行都创建一个新的实例。

// src property creates new IniConfigSource and sets value appropriately 
src.Configs["DATA"].Set("baa", "haaaaee"); 

// src property creates new IniConfigSource and essentially saves nothing 
src.Save(); 
+0

Downvote评论? –

+0

+1,因为你是对的,而其他人的低估是错误的。 – Fischermaen

2

问题是你正在使用两个src实例。将您的代码更改为:

public class Settings  
{ 
    public static readonly string fileName = "config.ini"; 
    private IConfigSource src; 
    private IConfigSource Src 
    { 
     get 
     { 
       CreateIfNotExists(); 
       return src; 
     } 
    }  
    public void test1() 
    { 
     //var src = new IniConfigSource(fileName); 
     Src.Configs["DATA"].Set("baa", "haaaaee");  
     Src.Save();  
    }  
    public void test2() 
    { 
     Src.Configs["DATA"].Set("baa", "haaaaee"); 
     Src.Save();   
    }  
    public Stream CreateIfNotExists()  
    { 
     if (!File.Exists(fileName))   
     { 
       Stream file = File.Create(fileName); 
       src = new IniConfigSource(fileName); 
       return file;   
     } 
     src = null; 
     return null;  
     } 
    }