-1

I am calling Redis with a batch request, though it seems that my code is continuing past the Await Task WhenAll statement before the cache has been updated. Am I awaiting the tasks in the wrong way?

ClearKey($"ordersList:{apiAccount.Id}");

var list = new List<Task<long>>();
IBatch batch = _redisDb.CreateBatch();
string listKey = $"ordersList:{apiAccount.Id}";

foreach (Order order in ordersList)
{
    var task = batch.ListRightPushAsync(listKey, Serialize(order));
    list.Add(task);
}

batch.Execute();
await Task.WhenAll(list.ToArray());

// Call other apps to say "cache is updated!" - This is triggering before cache actually gets updated.
Holland Risley
  • 6,969
  • 9
  • 25
  • 34
  • Try `Task t = Task.WhenAll(...)` then `await t;` After that take a look at `t.TaskStatus` and let us know what it is. Perhaps one of the tasks had an exception (`Faulted`)? – Ron Beyer Dec 30 '19 at 20:19
  • 1
    How do you know that it is triggering before the cache is updated? – Gabriel Luci Dec 30 '19 at 20:46
  • @RonBeyer if any of the tasks was faulted then the `Task.WhenAll` would also be faulted, and an exception would be thrown on the `await` statement. – Theodor Zoulias Dec 30 '19 at 21:34

1 Answers1

0

The problem was not with the await Task.WhenAll(...) statement but I was actually calling KeyDelete before this all happened, and I realised that I was not awaiting the deletion of the key before I re-cached the new orders list. This meant that if the orders list was empty then the method was completing before the key had actually been deleted. I have now replaced the Key Delete with the following async function which has solved my issue:

await ClearKey($"ordersList:{apiAccount.Id}");
       public async Task ClearKey(string key) {
            try
            {
                await _redisDb.KeyDeleteAsync(key);
            }
            catch (Exception ex)
            {
                // log exception
            }
      }
Holland Risley
  • 6,969
  • 9
  • 25
  • 34