Skip to content

Instantly share code, notes, and snippets.

@thecodejunkie
Last active December 15, 2015 09:09
Show Gist options
  • Save thecodejunkie/5236179 to your computer and use it in GitHub Desktop.
Save thecodejunkie/5236179 to your computer and use it in GitHub Desktop.
RequestStream rewrite
public RequestStream(Stream stream, long expectedLength, long thresholdLength, bool disableStreamSwitching)
{
this.thresholdLength = thresholdLength;
this.disableStreamSwitching = disableStreamSwitching;
this.stream = stream ?? this.CreateDefaultMemoryStream(expectedLength);
ThrowExceptionIfCtorParametersWereInvalid(this.stream, expectedLength, this.thresholdLength);
if (!this.MoveStreamOutOfMemoryIfExpectedLengthExceedExpectedLength(expectedLength))
{
this.MoveStreamOutOfMemoryIfContentsLengthExceedThresholdAndSwitchingIsEnabled();
}
if (!this.stream.CanSeek)
{
var task =
MoveToWritableStream();
task.Wait();
if (task.IsFaulted)
{
throw new InvalidOperationException("Unable to copy stream", task.Exception);
}
this.stream = task.Result;
}
this.stream.Position = 0;
}
private Task<Stream> MoveToWritableStream()
{
var tcs = new TaskCompletionSource<Stream>();
var buffer =
new MemoryStream((int)this.stream.Length);
this.stream.CopyTo(buffer, (source, destination, ex) =>
{
if (ex != null)
{
tcs.SetException(ex);
}
else
{
tcs.SetResult(destination);
}
});
return tcs.Task;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment