0

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?

macm
  • 544
  • 7
  • 21
  • This is a strange way to try to enforce a DB timeout. It is far simpler just to [specify the timeout setting by setting a property](https://stackoverflow.com/a/6234593/2791540). But if you insist on doing it this way, you should probably read [this answer](https://stackoverflow.com/a/48902866/2791540). – John Wu Sep 02 '22 at 18:13
  • @JohnWu does the CosmosDB provider support that? – Crowcoder Sep 02 '22 at 18:25
  • It must. I can’t tell you for sure but you should just try it, it wouldn’t be much of a database provider without being able to control the timeout. – John Wu Sep 02 '22 at 18:53

0 Answers0