initial commit
This commit is contained in:
48
Lab505.Script/RealSessionService.cs
Normal file
48
Lab505.Script/RealSessionService.cs
Normal file
@@ -0,0 +1,48 @@
|
||||
namespace Lab505.Script;
|
||||
|
||||
/// <summary>
|
||||
/// Ensures only one user runs a script in REAL mode at a time.
|
||||
/// Thread-safe lock with owner info for display.
|
||||
/// </summary>
|
||||
public sealed class RealSessionService
|
||||
{
|
||||
private readonly object _lock = new();
|
||||
|
||||
public record SessionInfo(int UserId, string Username, DateTime AcquiredAt);
|
||||
|
||||
public SessionInfo? Current { get; private set; }
|
||||
|
||||
public event Action? OnChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Try to acquire the real-mode lock for a user.
|
||||
/// Returns true if acquired (or user already holds it), false if someone else holds it.
|
||||
/// </summary>
|
||||
public bool TryAcquire(int userId, string username)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (Current is null)
|
||||
{
|
||||
Current = new SessionInfo(userId, username, DateTime.Now);
|
||||
OnChanged?.Invoke();
|
||||
return true;
|
||||
}
|
||||
return Current.UserId == userId; // same user can re-acquire
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Release the lock. Only the owner or a forced release.</summary>
|
||||
public void Release(int userId, bool force = false)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (Current is null) return;
|
||||
if (!force && Current.UserId != userId) return;
|
||||
Current = null;
|
||||
OnChanged?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsLocked => Current is not null;
|
||||
}
|
||||
Reference in New Issue
Block a user