Skip to content

Instantly share code, notes, and snippets.

@StephenCleary
Created August 24, 2022 21:11
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StephenCleary/42bb5144529ef52f596b07979c488f47 to your computer and use it in GitHub Desktop.
Save StephenCleary/42bb5144529ef52f596b07979c488f47 to your computer and use it in GitHub Desktop.
Producer/Consumer Stream
public sealed class ProducerConsumerStream
{
public static Stream Create(Func<Stream, Task> producer, PipeOptions? options = null)
{
var pipe = new Pipe(options ?? PipeOptions.Default);
var readStream = pipe.Reader.AsStream();
var writeStream = pipe.Writer.AsStream();
Run();
return readStream;
async void Run()
{
try
{
await producer(writeStream);
await writeStream.FlushAsync();
pipe.Writer.Complete();
}
catch (Exception ex)
{
pipe.Writer.Complete(ex);
}
}
}
}
@viruzzontop
Copy link

Great

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment