Created
August 24, 2022 21:11
-
-
Save StephenCleary/42bb5144529ef52f596b07979c488f47 to your computer and use it in GitHub Desktop.
Producer/Consumer Stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great