streamwriter declared static vs with an using statement

穿精又带淫゛_ 提交于 2019-12-24 00:26:46

问题


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:


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 :)



来源:https://stackoverflow.com/questions/17069833/streamwriter-declared-static-vs-with-an-using-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!