namespace Lab505.Script; /// /// Ensures only one user runs a script in REAL mode at a time. /// Thread-safe lock with owner info for display. /// 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; /// /// 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. /// 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 } } /// Release the lock. Only the owner or a forced release. 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; }