Skip to content

Commit 977faf2

Browse files
committed
Added async flushing of binary write streams
1 parent 286efeb commit 977faf2

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

Diff for: BinaryFileExtensions.cs

+5
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,11 @@ ex is IOException
127127

128128
await stream.WriteAsync(contents, i, writeBufferLength, cancellationToken);
129129
}
130+
131+
//make the flush operation explicit so it can be async
132+
//This is a use case for IAsyncDisposable as proposed in async streams, a candidate feature for C# 8.0, combined with a using statement enhancement that that proposal didn't cover. C# 7.x and below don't have a "nice" way to do asynchronous dispose, so the implicit Dispose() call from your using statement does the flush synchronously. The workaround is directly calling and awaiting on FlushAsync() so that the synchronous Dispose() doesn't have to synchronously flush.
133+
//https://stackoverflow.com/questions/21987533/streamwriter-uses-synchronous-invocation-when-calling-asynchronous-methods
134+
await stream.FlushAsync(cancellationToken);
130135
}
131136

132137
if (createTempFileFirst)

Diff for: FileExtensions.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ private static async Task<string> InternalReadAllTextAsync(string path, Encoding
117117
StringBuilder sb = new StringBuilder();
118118
while (true)
119119
{
120-
int read = await sr.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
120+
int read = await sr.ReadAsync(buffer, 0, buffer.Length); //TODO: add cancellationToken here?
121121
if (read == 0)
122122
{
123123
return sb.ToString();
@@ -226,12 +226,12 @@ private static async Task InternalWriteAllTextAsync(StreamWriter sw, string cont
226226
{
227227
int batchSize = Math.Min(DefaultBufferSize, count - sourceOffset);
228228
contents.CopyTo(sourceOffset, buffer, 0, batchSize);
229-
await sw.WriteAsync(buffer, 0, batchSize);
229+
await sw.WriteAsync(buffer, 0, batchSize); //TODO: add cancellationToken here?
230230
sourceOffset += batchSize;
231231
}
232232

233233
cancellationToken.ThrowIfCancellationRequested();
234-
await sw.FlushAsync();
234+
await sw.FlushAsync(); //TODO: add cancellationToken here?
235235
}
236236
finally
237237
{

0 commit comments

Comments
 (0)