Skip to content

[Proposal] Passing custom buffer to FileStream #52321

@sakno

Description

@sakno

Background and Motivation

FileStream has its own buffer for I/O. But it cannot be passed from outside. If the application requires a lot of FileStream objects with short lifetime there is not way to reuse the buffer between them. For instance, logging to files.Rotation of log files leads to dispose of old streams and create new ones. Also, it's reasonable to use memory pool (e.g. ArrayPool<T> or MemoryPool<T>) as a source of such buffers.

Proposed API

public class FileStream
{
  public FileStream(string path, FileMode mode, FileAccess access, FileShare share, Memory<byte> buffer, FileOptions options)
}

Usage Examples

var buffer = ArrayPool<byte>.Shared.Rent(4096);
using var fs = new FileStream("dummy.txt", FileMode.OpenOrCreate, FileAccess.Wrtie, FileShare.None, buffer.AsMemory(), FileOptions.None);

Alternative Designs

To mitigate risk of sharing the same buffer between different instances of file stream we could offer passing of memory pool:

public class FileStream
{
  public FileStream(string path, FileMode mode, FileAccess access, FileShare share, ArrayPool<byte> buffer, FileOptions options);
  public FileStream(string path, FileMode mode, FileAccess access, FileShare share, MemoryPool<byte> buffer, FileOptions options);
}

Risks

  • The same buffer can be passed to two or more streams
  • The buffer has been returned to the pool while FileStream still in use

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.IOuntriagedNew issue has not been triaged by the area owner

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions