2011-12-09 139 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;  
     } 
    }