0

Problem BackGround

I've read YungPeng's article (A Very Insightful Article) about Consistency between Redis Cache and SQL Database, and the double delete method looks simple enough, so I was considering to move it to our code(C#).

Specifically, I wanted to implement the mutable operation in double delete which can be summarized as follows according to YungPeng:

  1. Delete the entry in Redis;
  2. Create, update or delete the data to MySQL;
  3. Sleep for a while (say 500ms);
  4. Delete the entry in Redis again.

Questions

However, I have two questions about this:

  1. Waiting for the process to sleep 500ms, delete Redis then return to the caller (Step 3,4) seems very slow. Would it be reasonable to queue the task (that sleeps and clears Redis) first then return to caller without waiting for the task to complete?

  2. If my suggestion in question 1 is reasonable, how would I do it in C#? Would the following code be acceptable?

public async Task WriteOperation()
{
  await ClearRedis();
  await WriteDB();
  Task.Run( () => { // Sleep 0.5 seconds then clear Redis } ); // Notice how I didn't await this
  return;
}

Is it really ok to never await the Task? Will it ever be excuted? Would that Task finish roughly around 0.5 seconds?

Thanks in advance!

1

1 Answer 1

1

You can do something like this:

public async Task ClearRedisWithDelay()
{
    await Task.Delay(500);
    await ClearRedis();
}

and call

ClearRedisWithDelay

without await.

There are a few downsides with this approach: https://stackoverflow.com/a/54485904/14072498

Your own suggestion from your comment

 Task.Run(async () => { await Task.Delay(500); await ClearRedis(); })

will do the job in a new thread which should be acceptable.

The only guarantee regarding time, is a delay of min. 500 ms before calling ClearRedis.

Sign up to request clarification or add additional context in comments.

3 Comments

Right, something more like Task.Run(async () => { await Task.Delay(500); await ClearRedis(); }) ? Because I don't want to await this Task to slowdown my code.
That should work, you don't actually need to await ClearRedis(), Resharper gives a warning when skipping await in my code though, so keep it. Doesn't matter, your are in a new thread.
Updated my answer with an alternative to Task.Run

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.