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 Boolean _isDisposed;
private CancellationTokenSource _tokenSource = new CancellationTokenSource();
///
/// Gets the token of the current.
///
public CancellationToken Token {
get {
lock(this._syncLock) {
return this._isDisposed ? CancellationToken.None : this._tokenSource.Token;
}
}
}
///
/// Cancels the last referenced token and creates a new token source.
///
public void Cancel() {
lock(this._syncLock) {
if(this._isDisposed) {
return;
}
this._tokenSource.Cancel();
this._tokenSource.Dispose();
this._tokenSource = new CancellationTokenSource();
}
}
///
public void Dispose() => this.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(Boolean disposing) {
lock(this._syncLock) {
if(this._isDisposed) {
return;
}
if(disposing) {
this._tokenSource.Cancel();
this._tokenSource.Dispose();
}
this._isDisposed = true;
}
}
}
}