-
Notifications
You must be signed in to change notification settings - Fork 1.3k
CSHARP-5777: Avoid ThreadPool-dependent IO methods in sync API #1805
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -38,41 +38,14 @@ public static void EfficientCopyTo(this Stream input, Stream output) | |
|
|
||
| public static int Read(this Stream stream, byte[] buffer, int offset, int count, TimeSpan timeout, CancellationToken cancellationToken) | ||
| { | ||
| try | ||
| { | ||
| using var manualResetEvent = new ManualResetEventSlim(); | ||
| var readOperation = stream.BeginRead( | ||
| buffer, | ||
| offset, | ||
| count, | ||
| state => ((ManualResetEventSlim)state.AsyncState).Set(), | ||
| manualResetEvent); | ||
|
|
||
| if (readOperation.IsCompleted || manualResetEvent.Wait(timeout, cancellationToken)) | ||
| { | ||
| return stream.EndRead(readOperation); | ||
| } | ||
| } | ||
| catch (OperationCanceledException) | ||
| { | ||
| // Have to suppress OperationCanceledException here, it will be thrown after the stream will be disposed. | ||
| } | ||
| catch (ObjectDisposedException) | ||
| { | ||
| throw new IOException(); | ||
| } | ||
|
|
||
| try | ||
| { | ||
| stream.Dispose(); | ||
| } | ||
| catch | ||
| { | ||
| // Ignore any exceptions | ||
| } | ||
|
|
||
| cancellationToken.ThrowIfCancellationRequested(); | ||
| throw new TimeoutException(); | ||
| return ExecuteOperationWithTimeout( | ||
| stream, | ||
| (str, state) => str.Read(state.Buffer, state.Offset, state.Count), | ||
| buffer, | ||
| offset, | ||
| count, | ||
| timeout, | ||
| cancellationToken); | ||
| } | ||
|
|
||
| public static async Task<int> ReadAsync(this Stream stream, byte[] buffer, int offset, int count, TimeSpan timeout, CancellationToken cancellationToken) | ||
|
|
@@ -219,43 +192,18 @@ public static async Task ReadBytesAsync(this Stream stream, byte[] destination, | |
|
|
||
| public static void Write(this Stream stream, byte[] buffer, int offset, int count, TimeSpan timeout, CancellationToken cancellationToken) | ||
| { | ||
| try | ||
| { | ||
| using var manualResetEvent = new ManualResetEventSlim(); | ||
| var writeOperation = stream.BeginWrite( | ||
| buffer, | ||
| offset, | ||
| count, | ||
| state => ((ManualResetEventSlim)state.AsyncState).Set(), | ||
| manualResetEvent); | ||
|
|
||
| if (writeOperation.IsCompleted || manualResetEvent.Wait(timeout, cancellationToken)) | ||
| ExecuteOperationWithTimeout( | ||
BorisDog marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| stream, | ||
| (str, state) => | ||
| { | ||
| stream.EndWrite(writeOperation); | ||
| return; | ||
| } | ||
| } | ||
| catch (OperationCanceledException) | ||
| { | ||
| // Have to suppress OperationCanceledException here, it will be thrown after the stream will be disposed. | ||
| } | ||
| catch (ObjectDisposedException) | ||
| { | ||
| // It's possible to get ObjectDisposedException when the connection pool was closed with interruptInUseConnections set to true. | ||
| throw new IOException(); | ||
| } | ||
|
|
||
| try | ||
| { | ||
| stream.Dispose(); | ||
| } | ||
| catch | ||
| { | ||
| // Ignore any exceptions | ||
| } | ||
|
|
||
| cancellationToken.ThrowIfCancellationRequested(); | ||
| throw new TimeoutException(); | ||
| str.Write(state.Buffer, state.Offset, state.Count); | ||
| return true; | ||
| }, | ||
| buffer, | ||
| offset, | ||
| count, | ||
| timeout, | ||
| cancellationToken); | ||
| } | ||
|
|
||
| public static async Task WriteAsync(this Stream stream, byte[] buffer, int offset, int count, TimeSpan timeout, CancellationToken cancellationToken) | ||
|
|
@@ -325,5 +273,86 @@ public static async Task WriteBytesAsync(this Stream stream, OperationContext op | |
| count -= bytesToWrite; | ||
| } | ||
| } | ||
|
|
||
| private static TResult ExecuteOperationWithTimeout<TResult>(Stream stream, Func<Stream, (byte[] Buffer, int Offset, int Count), TResult> operation, byte[] buffer, int offset, int count, TimeSpan timeout, CancellationToken cancellationToken) | ||
| { | ||
| StreamDisposeCallbackState callbackState = null; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we have tests to test all the major cases here? Timeout, cancellation, success.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Tests added. |
||
| Timer timer = null; | ||
| CancellationTokenRegistration cancellationSubscription = default; | ||
| if (timeout != Timeout.InfiniteTimeSpan) | ||
| { | ||
| callbackState = new StreamDisposeCallbackState(stream); | ||
| timer = new Timer(DisposeStreamCallback, callbackState, timeout, Timeout.InfiniteTimeSpan); | ||
| } | ||
|
|
||
| if (cancellationToken.CanBeCanceled) | ||
| { | ||
| callbackState ??= new StreamDisposeCallbackState(stream); | ||
| cancellationSubscription = cancellationToken.Register(DisposeStreamCallback, callbackState); | ||
| } | ||
|
|
||
| try | ||
| { | ||
| var result = operation(stream, (buffer, offset, count)); | ||
| if (callbackState?.TryChangeStateFromInProgress(OperationState.Done) == false) | ||
| { | ||
| // if cannot change the state - then the stream was/will be disposed, throw here | ||
| throw new IOException(); | ||
| } | ||
|
|
||
| return result; | ||
| } | ||
| catch (IOException) | ||
| { | ||
| if (callbackState?.OperationState == OperationState.Cancelled) | ||
| { | ||
BorisDog marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| cancellationToken.ThrowIfCancellationRequested(); | ||
| throw new TimeoutException(); | ||
| } | ||
|
|
||
| throw; | ||
| } | ||
| finally | ||
| { | ||
| timer?.Dispose(); | ||
| cancellationSubscription.Dispose(); | ||
| } | ||
|
|
||
| static void DisposeStreamCallback(object state) | ||
| { | ||
| var disposeCallbackState = (StreamDisposeCallbackState)state; | ||
| if (!disposeCallbackState.TryChangeStateFromInProgress(OperationState.Cancelled)) | ||
| { | ||
| // if cannot change the state - then I/O was already succeeded | ||
BorisDog marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| disposeCallbackState.Stream.Dispose(); | ||
| } | ||
| catch (Exception) | ||
| { | ||
| // callbacks should not fail, suppress any exceptions here | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private record StreamDisposeCallbackState(Stream Stream) | ||
| { | ||
| private int _operationState = 0; | ||
|
|
||
| public OperationState OperationState => (OperationState)_operationState; | ||
|
|
||
| public bool TryChangeStateFromInProgress(OperationState newState) => | ||
| Interlocked.CompareExchange(ref _operationState, (int)newState, (int)OperationState.InProgress) == (int)OperationState.InProgress; | ||
| } | ||
|
|
||
| private enum OperationState | ||
| { | ||
| InProgress = 0, | ||
| Done, | ||
| Cancelled, | ||
| } | ||
| } | ||
| } | ||
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
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
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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
minor: can use expression body.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done