I'm trying to use StackExchange.Redis library to implement caching. One thing that I don't understand is how to properly use FireAndForget approach. Based on documentation I see that i have to provide CommandFlags.FireAndForget in case I don't want to wait until operation finishes.
I wrote test console application (net 4.7.2, StackExchange.Redis version is 2.0.601), I have 4 methods that emulates adding stuff to cache by single key:
//Async method with FireAndForget flag:
public static async Task<bool> AddAsyncWithFF(string key, object entity)
{
if (DataBase != null)
{
var redisValue = RedisValueHelper.GetRedisValue(entity);
if (redisValue != default(RedisValue))
{
return await DataBase.StringSetAsync(
key,
redisValue,
expiration.DateTime.Subtract(DateTime.Now),
flags: CommandFlags.FireAndForget);
}
}
return false;
}
//Async method without flag
return await DataBase.StringSetAsync(
key,
redisValue,
expiration.DateTime.Subtract(DateTime.Now),
flags: CommandFlags.None);
//Sync method with FireAndForget flag
DataBase.StringSetAsync(
key,
redisValue,
expiration.DateTime.Subtract(DateTime.Now),
flags: CommandFlags.FireAndForget);
//Sync method without flag
DataBase.StringSetAsync(
key,
redisValue,
expiration.DateTime.Subtract(DateTime.Now),
flags: CommandFlags.None);
I create 18 mb of random data and save per one key for testing purposes, here is the result (time measured using StopWatch class):
- Put sync data. Elapsed 229 ms
- Put sync with FireAndForget data. Elapsed 234 ms
- Put async data. Elapsed 12928 ms
- Put async with FireAndForget data. Elapsed 4508 ms
What I don't understand:
- Why sync calls with FF flag and without take the same time? It seems this flag is not in effect for sync calls.
- Why async method with FF flag takes longer than sync method?
- What is more interesting is that fact that async FF version takes 2-3 times less to execute than async without FF flag...
Ultimately I'd like to understand why can't I have asynchronous call with Fire and Forget flag that takes 200ms?
Thanks.