代码之家  ›  专栏  ›  技术社区  ›  user113476

重置或清除.NET内存流

  •  43
  • user113476  · 技术社区  · 16 年前

    .NET MemoryStream似乎没有.Reset或.Clear方法。

    我正在考虑使用以下代码来实现这一点:

    ms.Seek(0, IO.SeekOrigin.Begin)
    ms.SetLength(0)
    

    3 回复  |  直到 16 年前
        1
  •  -2
  •   omglolbah    16 年前

    memorystream没有重置/清除方法,因为它是冗余的。通过将其设置为零长度,可以清除它。

    memoryStream = new MemoryStream(memoryStream.Capacity());
    

    这将产生与初始化时大小相同的内存流。

    如果您真的想手动清除流,我怀疑您将不得不求助于通过元素循环。

        2
  •  90
  •   Andrew Bezzub    16 年前

    为什么需要重置内存流?你总是可以创建一个新的。或者您可以使用:

    memoryStream.SetLength(0);
    
        3
  •  29
  •   Rana Ian    11 年前

    public static void Clear(this MemoryStream source)
    {
      byte[] buffer = source.GetBuffer();
      Array.Clear(buffer, 0, buffer.Length);
      source.Position = 0;
      source.SetLength(0);
    }
    

    说MemoryStream.SetLength单独重置或清除MemoryStream是不正确的,因为SetLength仅在长度超过当前缓冲区长度时才清除内部缓冲区数组。

        4
  •  1
  •   bunjeeb    5 年前

    我曾经 我调用GC来强制执行完全收集。 我发现那么大 威尔卡住了 LOH公司 再加上一行

    public static void Clear(MemoryStream ms)
    {
        var buffer = ms.GetBuffer();
        Array.Clear(buffer, 0, buffer.Length);
        ms.Position = 0;
        ms.SetLength(0);
        ms.Capacity = 0; // <<< this one ******
    }
    

    我点击了 看 Capacity 实现,我发现了这一点(我稍微简化了生成的代码-我正在使用Resharper):

    public virtual int Capacity
    {
      get
      { .... // some code }
      set
      {
        if ((long) value < this.Length) { // throw some ex }
        if (!this._isOpen) { // some another code }
        if (!this._expandable && value != this.Capacity) { //MemoryStreamNotExpandable }
        if (!this._expandable || value == this._capacity) return;
        if (value > 0)
        {
          byte[] numArray = new byte[value];
          if (this._length > 0)
            Buffer.InternalBlockCopy((Array) this._buffer, 0, (Array) numArray, 0, this._length);
          this._buffer = numArray;
        }
        else
          this._buffer = (byte[]) null; /// <<<< that's it! I need this one
        this._capacity = value;
      }
    }
    

    所以它正在清除缓冲区,我不确定这是否正确!

    推荐文章