Skip to content

Instantly share code, notes, and snippets.

@SteveDunn
Last active May 4, 2022 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SteveDunn/86cece0d587c6d79ca9c4a284f597a1f to your computer and use it in GitHub Desktop.
Save SteveDunn/86cece0d587c6d79ca9c4a284f597a1f to your computer and use it in GitHub Desktop.
WebApi client disconnection
[HttpGet(Name = "GetWeatherForecast")]
public async Task<IEnumerable<WeatherForecast>> Get()
{
//pass this around to long running tasks
CancellationToken cancellationToken = HttpContext.RequestAborted;
if (cancellationToken.IsCancellationRequested)
{
throw null!; // or whatever you want to do
}
return await DoItSlowly(++_callerCount, cancellationToken);
}
private async Task<IEnumerable<WeatherForecast>> DoItSlowly(int callerCount,
CancellationToken cancellationToken)
{
List<WeatherForecast> l = new List<WeatherForecast>();
for (int i = 0; i < 5; i++)
{
cancellationToken.ThrowIfCancellationRequested();
_logger.LogWarning($"Caller id = {callerCount}, index = {i}");
await Task.Delay(1000);
l.Add(new WeatherForecast
{
Date = DateTime.Now.AddDays(i),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
});
}
return l.ToArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment