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);
}
}