streamwriter declared static vs with an using stat

2019-07-16 01:12发布

I'm VERY new to C# so please allow me some ignorance :) (I've tried searching around to understand the reason for the difference in performance I'm seeing but as of yet don't have a definitive answer so I thought I'd ask the knowledgable audience on here...)

Basically... if I use streamwriter something like:

public static class Logging
{
  readonly static object DebugWriter = new object();

  public static void Log(string msg)
  {
    lock (DebugWriter)
    {
      using (StreamWriter writer = new StreamWriter("Debug.txt", true))
      {
        writer.WriteLine(DateTime.UtcNow.ToString("HH:mm:ss.ffff") + " " + msg);
      }
    }
  }
}

then assuming I send a large amount of text out via this class I see a noticeable hit on CPU. However if I instead write it something along the lines of:

public static class Logging
{
  readonly static object DebugWriter = new object();
  static StreamWriter lwriter = new StreamWriter("LocalDrivenDebug.txt", true) { AutoFlush = true };

  public static void Log(string msg)
  {
    lock (DebugWriter)
    {
        lwriter.WriteLine(DateTime.UtcNow.ToString("HH:mm:ss.ffff") + " " + msg);
    }
  }
}

Then I see pretty much no hit on the CPU at all.

Is the above caning the CPU purely through inialisation and disposal caused by the using statement? (If so what the hell is C# doing to eat so much CPU???) - Given it's a static class and I've forced autoflush, surely the same applies to the second version or does its disposal get acted on differently and hence chew up less CPU time?

I can only assume I'm missing something obvious. So hopefully someone out there can enlighten me as I 'thought' you were supposed to use the using statement as a safer/more convenient way of doing the disposal?

1条回答
一纸荒年 Trace。
2楼-- · 2019-07-16 01:44

The second snippet has two properties : - It doesn't recreate the writer, which can help if you call log many times. - It doesn't dispose the writer, which means the text you are writing is not flushed to disk yet, but rather kept in memory for later flushing ! On the other end, you write on disk every call to log with the first snippet.

All in all, these two effects should explain the noticeable difference you see :)

查看更多
登录 后发表回答