I'm having a difficult time understanding why my database request is not cancelling out. I know the request is taking about 3.5 seconds. If I pause the code before hitting the database request, I can get the catch to fire but obviously I want to cancel the task if it is taking longer than 100ms, which it is.
public async Task<IEnumerable<Foo>> GetDataFromCosmos(string partition)
{
var partitionKey = new PartitionKey(partition);
CancellationTokenSource s = new CancellationTokenSource(100);//<--100 ms
s.Token.ThrowIfCancellationRequested();
sw.Reset();
try
{
var result =
await _dbContext.GetItemsInPartitionAsStreamsAsync<Foo>(CollectionName, partitionKey,s.Token);
sw.Stop();
if (sw.ElapsedMilliseconds > 3500)
_logger.LogWarning(
$"{nameof(GetDataFromCosmos)} data is taking a long time to return: {sw.ElapsedMilliseconds} ms");
return result;
}
catch (OperationCanceledException exp)
{
_logger.LogError("timed out");
throw;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
The result is consistently GetDatFromCosmos data is taking a long time to return: 7550 ms
What am I missing here?