Skip to content

CancellationTokenSource not work #236

@303248153

Description

@303248153

I need to stop the container after it runs longer than the time I give, then I try to use CancellationTokenSource, here is my code:

public static async Task DockerCancell()
{
	var cert = new CertificateCredentials(new X509Certificate2(CertPath, CertPassword));
	var configuration = new DockerClientConfiguration(new Uri("https://docker-1:2376"), cert);
	var client = configuration.CreateClient();
	var createResult = await client.Containers.CreateContainerAsync(new CreateContainerParameters()
	{
		Image = Image,
		Name = Guid.NewGuid().ToString(),
		WorkingDir = "/workdir",
		HostConfig = new HostConfig() { AutoRemove = true },
		Cmd = new[] { "sleep", "3" }
	});
	await client.Containers.StartContainerAsync(createResult.ID, new ContainerStartParameters());
	var token = new CancellationTokenSource();
	token.CancelAfter(1000);
	await client.Containers.WaitContainerAsync(createResult.ID, token.Token);
	Console.WriteLine("shouldn't be here");
}

It always output "shouldn't be here", looks like cancellation token didn't work for this api.
Further more, not only CancelAfter, Cancel is not work too:

public static async Task DockerCancell()
{
	var cert = new CertificateCredentials(new X509Certificate2(CertPath, CertPassword));
	var configuration = new DockerClientConfiguration(new Uri("https://docker-1:2376"), cert);
	var client = configuration.CreateClient();
	var createResult = await client.Containers.CreateContainerAsync(new CreateContainerParameters()
	{
		Image = Image,
		Name = Guid.NewGuid().ToString(),
		WorkingDir = "/workdir",
		HostConfig = new HostConfig() { AutoRemove = true },
		Cmd = new[] { "sleep", "3" }
	});
	await client.Containers.StartContainerAsync(createResult.ID, new ContainerStartParameters());
	var token = new CancellationTokenSource();
	// token.CancelAfter(1000);
	var task = client.Containers.WaitContainerAsync(createResult.ID, token.Token);
	await Task.Delay(1);
	token.Cancel();
	await task;
	Console.WriteLine("shouldn't be here");
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions