Files
2026-05-09 03:55:56 +08:00

115 lines
2.2 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using BetterGenshinImpact.Model;
using System.Threading;
namespace BetterGenshinImpact.Core.Script;
public class CancellationContext : Singleton<CancellationContext>
{
private readonly object _sync = new();
public CancellationTokenSource Cts { get; private set; } = new();
public bool IsManualStop { get; private set; }
public bool IsCancellationRequested
{
get
{
lock (_sync)
{
return !disposed && Cts.IsCancellationRequested;
}
}
}
private bool disposed;
public CancellationToken GetActiveToken()
{
lock (_sync)
{
if (disposed)
{
Cts = new CancellationTokenSource();
IsManualStop = false;
disposed = false;
}
return Cts.Token;
}
}
public void Set()
{
lock (_sync)
{
Cts = new CancellationTokenSource();
IsManualStop = false;
disposed = false;
}
}
public void ManualCancel()
{
CancellationTokenSource cts;
lock (_sync)
{
if (disposed)
{
return;
}
IsManualStop = true;
cts = Cts;
}
try
{
cts.Cancel();
}
catch (ObjectDisposedException)
{
// 并发 Clear 可能已释放 CTS这里视为已取消/已清理。
}
}
public void Cancel()
{
CancellationTokenSource cts;
lock (_sync)
{
if (disposed)
{
return;
}
cts = Cts;
}
try
{
cts.Cancel();
}
catch (ObjectDisposedException)
{
// 并发 Clear 可能已释放 CTS这里视为已取消/已清理。
}
}
public void Clear()
{
CancellationTokenSource cts;
lock (_sync)
{
if (disposed)
{
return;
}
cts = Cts;
disposed = true;
}
cts.Dispose();
}
}