是Stream.Copy管道? [英] Is Stream.Copy piped?

查看:180
本文介绍了是Stream.Copy管道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我写一个TCP代理代码。
我从输入流中读取和写入到输出流。
我知道Stream.Copy使用缓冲区,但我的问题是:
是否Stream.Copy方法写入到输出流,同时获取从输入流或一个环状的下一大块读从输入块,写块到输出中,从输入等读块?

Suppose I am writing a tcp proxy code. I am reading from the incoming stream and writing to the output stream. I know that Stream.Copy uses a buffer, but my question is: Does the Stream.Copy method writes to the output stream while fetching the next chunk from the input stream or it a loop like "read chunk from input, write chunk to ouput, read chunk from input, etc" ?

推荐答案

下面的 CopyTo从在.NET 4.5的实现:

Here's the implementation of CopyTo in .NET 4.5:

private void InternalCopyTo(Stream destination, int bufferSize)
{
    int num;
    byte[] buffer = new byte[bufferSize];
    while ((num = this.Read(buffer, 0, buffer.Length)) != 0)
    {
        destination.Write(buffer, 0, num);
    }
}



因此​​,大家可以看到,它从源头上读取,然后的写入目标。这或许可以得到改善;)

So as you can see, it reads from the source, then writes to the destination. This could probably be improved ;)

编辑:的下面是一个可能实现的管道版本

here's a possible implementation of a piped version:

public static void CopyToPiped(this Stream source, Stream destination, int bufferSize = 0x14000)
{
    byte[] readBuffer = new byte[bufferSize];
    byte[] writeBuffer = new byte[bufferSize];

    int bytesRead = source.Read(readBuffer, 0, bufferSize);
    while (bytesRead > 0)
    {
        Swap(ref readBuffer, ref writeBuffer);
        var iar = destination.BeginWrite(writeBuffer, 0, bytesRead, null, null);
        bytesRead = source.Read(readBuffer, 0, bufferSize);
        destination.EndWrite(iar);
    }
}

static void Swap<T>(ref T x, ref T y)
{
    T tmp = x;
    x = y;
    y = tmp;
}



基本上,它读取一大块同步,开始将其异步复制到目标,然后读取下一个块,并等待写入完成

Basically, it reads a chunk synchronously, starts to copy it to the destination asynchronously, then read the next chunk and waits for the write to complete.

我跑了几个性能测试:


  • 使用的MemoryStream S,没想到一个显著的改善,因为它不使用IO完成端口(据我所知);而事实上,性能几乎相同

  • 使用不同的驱动器的文件,我预计管道版本有更好的表现,但它不...它实际上是速度稍慢(5〜 10%)

  • using MemoryStreams, I didn't expect a significant improvement, since it doesn't use IO completion ports (AFAIK); and indeed, the performance is almost identical
  • using files on different drives, I expected the piped version to perform better, but it doesn't... it's actually slightly slower (by 5 to 10%)

因此,它显然不带来任何好处,这可能是为什么它没有实现这种方式的原因。 ..

So it apparently doesn't bring any benefit, which is probably the reason why it isn't implemented this way...

这篇关于是Stream.Copy管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆