Skip to content

Feature Request: Add Stream.CreateConnectedStreams API #43101

@geoffkizer

Description

@geoffkizer

Background and Motivation

It's often convenient to have a simple in-memory producer/consumer stream. We have a few variations of this in our test code, e.g. VirtualNetwork. You can also achieve this by using a loopback socket or a named pipe; however these approaches are unnecessarily difficult to use and the perf likely isn't great, since it's copying buffers through the OS.

Proposed API

namespace System.IO
{
  class Stream
  {
    (Stream stream1, Stream stream2) CreateConnectedStreams(int maxBufferSize = 16384, bool duplex = true);
  }
}

If duplex is true, then both streams can both read and write. If duplex is false, then stream1 is write-only and stream2 is read-only. Alternatively, we could have two separate methods for clarity.

We may want to have a distinguished type for the returned Streams, like ConnectedStream, just in case we ever want to add more APIs to it.

Usage Examples

    (Stream stream1, Stream stream2) = CreateConnectedStreams();
    stream1.Write(Encoding.UTF8.GetBytes("Hello world!\n"));
    byte[] buffer = new byte[4096];
    int bytesRead = stream2.Read(buffer);
    Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, bytesRead));

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.IO

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions