Can't cancel Dapr client request

134 views Asked by At

I'm trying to cancel a long running request on a web api server using a CancellationToken in a call on a DaprClient. I'm basing the code on that found at "Get started with Dapr" article on microsoft.com

private static CancellationTokenSource cts;
public async Task OnGet()
{
    cts = new CancellationTokenSource();
    var forecasts = await _daprClient.InvokeMethodAsync<IEnumerable<WeatherForecast>>(
        HttpMethod.Get,
        "MyBackEnd",
        "weatherforecast",
        cts.Token);

    ViewData["WeatherForecastData"] = forecasts;
    cts.Dispose();
}

The user can stop the processing:

public void OnPost()
{
    cts.Cancel();
    cts.Dispose();
    ViewData["WeatherForecastData"] = new List<WeatherForecast>();
}

The server controller registers a cancellation token:

[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get(CancellationToken token)
{
    bool cancelled = false;
    token.Register(() => {
        Debug.WriteLine("Cancelled");
        cancelled = true;
    });

    List<WeatherForecast> forecasts = new List<WeatherForecast>();
    for (int i = 1; i < 6; i++)
    {
        if (cancelled)
        {
            Debug.WriteLine($"Cancelled after {i} iterations");
            break;
        }
        Debug.WriteLine($"Iter #{i}");
        forecasts.Add(new WeatherForecast
        {
            Date = DateTime.Now.AddDays(i),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        });
        Task.Delay(1000).Wait();
    }

    return forecasts;
}

}

When I cancel a request from an Http client call, the server code sees it and stops:

private static CancellationTokenSource cts;
public async Task OnGet()
{
    cts = new CancellationTokenSource();
    string serverUrl = $"http://mybackend/WeatherForecast";
    List<WeatherForecast>? forecasts = await _httpClient.GetFromJsonAsync<List<WeatherForecast>>(serverUrl, cts.Token);
    ViewData["WeatherForecastData"] = forecasts;
    cts.Dispose();
}

But with the Dapr version above, the server code keeps going after the cancellation.

I expect this has something to do with the sidecars, but I need to be able to stop the processing.

I have a Visual Studio solution on GitHub that demonstrates the issue: github.com link

0

There are 0 answers