Gurpreet Kailey
Gurpreet Kailey

Reputation: 669

StackExchange.Redis, use CancellationToken with IDatabase.StringGetAsync()

I have created .Net 8 version API. I'm using Azure Redis cache in the application.

The Nuget package used to interact with Azure Redis is 'StackExchange.Redis'. To fetch the data there is function given IDatabase.StringGetAsync() but there is no provision to provide CancellationToken in this function.

How can I achieve this operation timeout capability with StringGetAsync() function. I want to achieve, if this GET operation take more than 1 second then the call be aborted.

Upvotes: 2

Views: 840

Answers (2)

Daniel Waechter
Daniel Waechter

Reputation: 2763

So, the thing you want to do is to provide a timeout to StringGetAsync. You can do that, just not with a CancellationToken, currently, since StackExchange.Redis doesn't support that (#1039).

The library's documentation describes how to provide configuration options for timeouts when you connect to Redis. As far as I can tell, you can only provide this globally for the connection, not for each operation, so you'll have to manage that yourself.

It's likely you want to set both the synchronous and asynchronous timeout options to the same value, so I'm doing so in the example code below.

var options = ConfigurationOptions.Parse("localhost");
options.AsyncTimeout = 1000;
options.SyncTimeout = options.AsyncTimeout;
ConnectionMultiplexer conn = ConnectionMultiplexer.Connect(options); // Store and re-use this

...

var db = conn.GetDatabase();
var redisValue = await db.StringGetAsync(key); // Can now time out if it takes longer than 1 second

Alternatively, in you can also wait on the cancellation token with Task.WaitAsync, so that at least the current context can be cancelled even if Redis doesn't time out. This won't cancel the Redis operation in that case, but it will return control to your method.

var redisValue = await db.StringGetAsync(key).WaitAsync(cancellationToken);

You can see another example in their test cases here.

Upvotes: 1

ekvalizer
ekvalizer

Reputation: 148

Task.WhenAny(db.StringGetAsync(), Task.Delay(1000))

Upvotes: -1

Related Questions