Skip to content

Commit

Permalink
Use TaskCompletionSource to async wait for population
Browse files Browse the repository at this point in the history
  • Loading branch information
peppy committed Jun 11, 2024
1 parent dd37749 commit a19ab1c
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions GlobalRankLookupCache/Controllers/BeatmapRankCache.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Threading;

Expand All @@ -23,11 +22,13 @@ public BeatmapRankCache(int beatmapId, string highScoresTable)

private DateTimeOffset lastPopulation;

private readonly ManualResetEventSlim populated = new ManualResetEventSlim();
private readonly TaskCompletionSource<bool> populated = new TaskCompletionSource<bool>();

public async Task<(int position, int total)> Lookup(int score)
{
if (!waitForPopulation())
bool success = await waitForPopulation();

if (!success)
{
// do quick lookup
using (var db = await Program.GetDatabaseConnection())
Expand Down Expand Up @@ -60,14 +61,16 @@ public BeatmapRankCache(int beatmapId, string highScoresTable)
return (scores.Count - (result < 0 ? ~result : result), scores.Count);
}

private bool waitForPopulation()
private async Task<bool> waitForPopulation()
{
if (populated.IsSet)
if (populated.Task.IsCompleted)
return true;

queuePopulation();

return populated.Wait(1000);
await Task.WhenAny(Task.Delay(1000), populated.Task);

return populated.Task.IsCompleted;
}

private void queuePopulation()
Expand Down Expand Up @@ -127,7 +130,7 @@ private async Task repopulateScores()
}

Scores = scores;
populated.Set();
populated.SetResult(true);
lastPopulation = DateTimeOffset.Now;
}
catch
Expand Down

0 comments on commit a19ab1c

Please sign in to comment.