2014-05-05 46 views
1

我有一個C#程序,使用簡單的日誌記錄類來(你猜對了)創建日誌文件。下面是我爲類構造函數所使用的代碼。我想知道是否因爲它只使用一個線程,我真的需要在流上使用lock嗎?必須在單線程程序中使用鎖嗎?

public Logger(MemoryStream stream) 
    : base(stream) 
{ 

    try 
    { 
     // Flush the buffers automatically 
     this.AutoFlush = true; 

     lock (this.BaseStream) // <-- Do I need this? 
     { 
      // Writes header to log file 
      this.WriteLine("Date & Time: " + DateTime.Now.ToString()); 
      this.WriteLine("OS: " + OSVersion.GetOSVersion()); 
      this.WriteLine(); 
     } 
    } 
    catch (Exception ex) 
    { 
     Debug.WriteLine(ex); 
    } 
} 

UPDATE:不好意思拿這個問題偏離軌道,但我發現,它使用多個線程。我的下一個問題是,對this.BaseStream鎖,是否可以訪問使用WriteTo將其複製到另一個流,像這樣:

lock (this.BaseStream) 
{ 
    using (FileStream fileStream = new FileStream(strNewFileName, FileMode.Create, FileAccess.Write)) 
    { 
     (this.BaseStream as MemoryStream).WriteTo(fileStream); 
    } 
} 

回答

1

你不應該鎖定您要使用的對象,創建一個鎖object你可以用它來代替。

private readonly object myLock = new object(); 

void DoThreadedStuff(){ 
    lock(myLock){ 
    //Anything that requires a lock here. 
    } 
} 

這將只鎖定myLock對象,而不是流本身。

相關問題