initial commit
This commit is contained in:
39
Lab505.Script/ScriptCancelService.cs
Normal file
39
Lab505.Script/ScriptCancelService.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
namespace Lab505.Script;
|
||||
|
||||
/// <summary>Per-user CancellationTokenSource registry. Thread-safe.</summary>
|
||||
public sealed class ScriptCancelService
|
||||
{
|
||||
private readonly object _lock = new();
|
||||
private readonly Dictionary<int, CancellationTokenSource> _map = new();
|
||||
|
||||
public CancellationToken Register(int userId, out CancellationTokenSource cts)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_map.TryGetValue(userId, out var old)) { old.Cancel(); old.Dispose(); }
|
||||
cts = new CancellationTokenSource();
|
||||
_map[userId] = cts;
|
||||
return cts.Token;
|
||||
}
|
||||
}
|
||||
|
||||
public void Cancel(int userId)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_map.TryGetValue(userId, out var cts)) cts.Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
public void Clear(int userId)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_map.TryGetValue(userId, out var cts)) { cts.Dispose(); _map.Remove(userId); }
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy single-user helpers (kept for backward compat)
|
||||
public void Cancel() { lock (_lock) { foreach (var c in _map.Values) c.Cancel(); } }
|
||||
public void Clear() { lock (_lock) { foreach (var c in _map.Values) c.Dispose(); _map.Clear(); } }
|
||||
}
|
||||
Reference in New Issue
Block a user