Last active
December 15, 2015 09:09
-
-
Save thecodejunkie/5236179 to your computer and use it in GitHub Desktop.
RequestStream rewrite
This file contains hidden or 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 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