本文介绍了StreamWriter的声明为static VS与using语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的C#所以请允许我一些无知:)(我试图摸索,以了解在性能我看到差异的原因,但作为然而没有一个明确的答案,所以我想我会问见地的观众在这里...)

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

基本上,如果我使用的StreamWriter是这样的:

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

再假设我发送大量文本出来,通过这个类我看到CPU的一个显着的打击。但是,如果我不是写出来的线沿线的东西:

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

然后我看到pretty的多少没有命中CPU上的。

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

就是上面鞭刑的CPU完全通过inialisation和处置造成使用声明? (如果是的话到底是什么C#干什么吃这么多CPU ???) - 由于这是一个静态类,我已经被迫自动冲洗,当然同样适用于第二个版本还是它的处置获得采取行动不同,因此咀嚼较少的CPU时间?

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?

我只能假设我失去了一些东西明显。所以希望有人在那里能开导我,我'想'你应该使用using语句作为做处理更安全/更便捷的途径?

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?

推荐答案

第二个片段有两个属性: - 它不会重新作家,它可以帮助你通话记录很多次。 - 它不处置的作家,这意味着你正在写的文字是不是刷新到磁盘然而,而是保存在内存中供以后冲洗!在另一端,你写在磁盘上的每个呼叫记录的第一个片段。

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

这篇关于StreamWriter的声明为static VS与using语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 01:19
查看更多