using System; using System.Threading; namespace Swan.Threading { /// /// Acts as a but with reusable tokens. /// public sealed class CancellationTokenOwner : IDisposable { private readonly object _syncLock = new object(); private bool _isDisposed; private CancellationTokenSource _tokenSource = new CancellationTokenSource(); /// /// Gets the token of the current. /// public CancellationToken Token { get { lock (_syncLock) { return _isDisposed ? CancellationToken.None : _tokenSource.Token; } } } /// /// Cancels the last referenced token and creates a new token source. /// public void Cancel() { lock (_syncLock) { if (_isDisposed) return; _tokenSource.Cancel(); _tokenSource.Dispose(); _tokenSource = new CancellationTokenSource(); } } /// public void Dispose() => Dispose(true); /// /// Releases unmanaged and - optionally - managed resources. /// /// true to release both managed and unmanaged resources; false to release only unmanaged resources. private void Dispose(bool disposing) { lock (_syncLock) { if (_isDisposed) return; if (disposing) { _tokenSource.Cancel(); _tokenSource.Dispose(); } _isDisposed = true; } } } }