Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions src/Docker.DotNet/Endpoints/StreamUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ internal static async Task MonitorStreamAsync(Task<Stream> streamTask, DockerCli
using (var reader = new StreamReader(stream, new UTF8Encoding(false)))
{
string line;
while ((line = await reader.ReadLineAsync()) != null)
while ((line = await reader.ReadLineAsync().WithCancellation(cancel)) != null)
{
progress.Report(line);
}
Expand All @@ -40,7 +40,7 @@ internal static async Task MonitorStreamForMessagesAsync<T>(Task<Stream> streamT
string line;
try
{
while ((line = await reader.ReadLineAsync()) != null)
while ((line = await reader.ReadLineAsync().WithCancellation(cancel)) != null)
{
var prog = client.JsonSerializer.DeserializeObject<T>(line);
if (prog == null) continue;
Expand All @@ -57,5 +57,19 @@ internal static async Task MonitorStreamForMessagesAsync<T>(Task<Stream> streamT
}
}
}

private static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
{
if (task != await Task.WhenAny(task, tcs.Task))
{
throw new OperationCanceledException(cancellationToken);
}
}

return await task;
}
}
}
11 changes: 11 additions & 0 deletions test/Docker.DotNet.Tests/ISystemOperations.Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,17 @@ public async Task MonitorEventsAsync_Succeeds()
await _client.Images.DeleteImageAsync($"{repository}:{tag}", new ImageDeleteParameters());
}

[Fact]
public async Task MonitorEventsAsync_EmptyContainersList_CanBeCancelled()
{
var cts = new CancellationTokenSource();

cts.CancelAfter(1000);
var task = _client.System.MonitorEventsAsync(new ContainerEventsParameters(), new Progress(), cts.Token);

await Assert.ThrowsAsync<OperationCanceledException>(async () => await task);
}

class Progress : IProgress<JSONMessage>
{
internal Action<JSONMessage> _onCalled;
Expand Down