77 lines
2.6 KiB
C#
77 lines
2.6 KiB
C#
using Sarand.Net.Standard.Base.Core;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
using System.Threading;
|
|
|
|
namespace Sarand.Net.Standard.Base.Tasks
|
|
{
|
|
//=======================================================================
|
|
public class SacsTaskData : SacsDisposable
|
|
{
|
|
//-------------------------------------------------------------------
|
|
// Data members.
|
|
// Cancellation token source - allows task cancellation to be triggered
|
|
// if the cancellation tokden wasn't supplied on construction.
|
|
private CancellationTokenSource cancellationTokenSource = null;
|
|
|
|
//-------------------------------------------------------------------
|
|
// Construction.
|
|
public SacsTaskData (CancellationToken? cancellationToken)
|
|
{
|
|
if (cancellationToken != null)
|
|
{
|
|
// Cancell token supplied on construction
|
|
// - cancellation is controlled by a higher level task.
|
|
CancellationToken = (CancellationToken)cancellationToken;
|
|
}
|
|
else
|
|
{
|
|
// Cancellation token not supplied - cancellation can be triggered here.
|
|
cancellationTokenSource = new CancellationTokenSource();
|
|
CancellationToken = cancellationTokenSource.Token;
|
|
}
|
|
}
|
|
protected override void Dispose (bool disposing)
|
|
{
|
|
if (disposing)
|
|
{
|
|
if (cancellationTokenSource != null)
|
|
{
|
|
cancellationTokenSource.Cancel();
|
|
cancellationTokenSource.Dispose();
|
|
}
|
|
cancellationTokenSource = null;
|
|
}
|
|
}
|
|
|
|
//-------------------------------------------------------------------
|
|
// Properties.
|
|
public bool Debug { get; set; }
|
|
|
|
//-------------------------------------------------------------------
|
|
// C a n c e l l a t i o n
|
|
//-------------------------------------------------------------------
|
|
/// <summary>Token to allow the async request to be cancelled.</summary>
|
|
public CancellationToken CancellationToken { get; }
|
|
/// <summary>Gets whether cancellation has been requested.</summary>
|
|
public bool IsCancellationRequested { get { return CancellationToken.IsCancellationRequested; } }
|
|
/// <summary>Throws a System.OperationCanceledException if this token has had cancellation requested.</summary>
|
|
public void ThrowIfCancellationRequested()
|
|
{
|
|
CancellationToken.ThrowIfCancellationRequested();
|
|
}
|
|
/// <summary>Can cancellation be triggered here?</summary>
|
|
public bool CanBeCancelled { get { return cancellationTokenSource != null; } }
|
|
public bool TriggerCancellation ()
|
|
{
|
|
if (!CanBeCancelled) return false;
|
|
cancellationTokenSource.Cancel();
|
|
return true;
|
|
}
|
|
|
|
//-------------------------------------------------------------------
|
|
}
|
|
//=======================================================================
|
|
}
|