使用DaprClient调用接口时CancellationToken无法取消请求的问题
DaprClient调用时CancellationToken无法取消服务端请求的问题
我在Web API服务器上尝试通过DaprClient调用时使用CancellationToken取消长时间运行的请求,代码基于微软《Get started with Dapr》文档实现。
客户端调用代码(使用DaprClient)
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(); }
请求取消触发代码
public void OnPost() { cts.Cancel(); cts.Dispose(); ViewData["WeatherForecastData"] = new List<WeatherForecast>(); }
服务端控制器代码
[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; }
HttpClient直接调用的正常代码
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(); }
问题现象
使用HttpClient直接调用时,取消操作可正常触发服务端停止处理;但使用上述DaprClient调用的方式时,触发取消后服务端代码仍会继续执行。推测该问题与Dapr Sidecar有关,需要实现请求取消的功能。示例项目已上传至GitHub仓库(garzooma/CancelDemoBlazor)
内容的提问来源于stack exchange,提问作者Greg Arzoomanian
相关产品推荐
相关产品推荐

