block and lock for loading of discord users

This commit is contained in:
Ben 2025-04-17 15:51:20 +02:00
parent 16b5ee4fd1
commit abdc7a0ab1
No known key found for this signature in database
GPG Key ID: 0F16E812E736C24B
2 changed files with 17 additions and 11 deletions

View File

@ -25,7 +25,7 @@ namespace BiblioTech.Rewards
public async Task RunRoleGiver(Func<IRoleGiver, Task> action)
{
var context = await OpenRoleModifyContext();
var context = OpenRoleModifyContext();
var mapper = new RoleMapper(context);
await action(mapper);
}
@ -37,7 +37,7 @@ namespace BiblioTech.Rewards
public async Task IterateUsersWithRoles(Func<IRoleGiver, IUser, ulong, Task> onUserWithRole, Func<IRoleGiver, Task> whenDone, params ulong[] rolesToIterate)
{
var context = await OpenRoleModifyContext();
var context = OpenRoleModifyContext();
var mapper = new RoleMapper(context);
foreach (var user in context.Users)
{
@ -52,10 +52,10 @@ namespace BiblioTech.Rewards
await whenDone(mapper);
}
private async Task<RoleModifyContext> OpenRoleModifyContext()
private RoleModifyContext OpenRoleModifyContext()
{
var context = new RoleModifyContext(GetGuild(), userRepo, log, rewardsChannel);
await context.Initialize();
context.Initialize();
return context;
}

View File

@ -11,6 +11,7 @@ namespace BiblioTech.Rewards
private Dictionary<ulong, IGuildUser> users = new();
private Dictionary<ulong, SocketRole> roles = new();
private DateTime lastLoad = DateTime.MinValue;
private readonly object _lock = new object();
private readonly SocketGuild guild;
private readonly UserRepo userRepo;
@ -25,15 +26,20 @@ namespace BiblioTech.Rewards
this.rewardsChannel = rewardsChannel;
}
public async Task Initialize()
public void Initialize()
{
var span = DateTime.UtcNow - lastLoad;
if (span > TimeSpan.FromMinutes(10))
lock (_lock)
{
lastLoad = DateTime.UtcNow;
log.Log("Loading all users and roles...");
this.users = await LoadAllUsers(guild);
this.roles = LoadAllRoles(guild);
var span = DateTime.UtcNow - lastLoad;
if (span > TimeSpan.FromMinutes(10))
{
lastLoad = DateTime.UtcNow;
log.Log("Loading all users and roles...");
var task = LoadAllUsers(guild);
task.Wait();
this.users = task.Result;
this.roles = LoadAllRoles(guild);
}
}
}