// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Diagnostics;
using System.Threading.Tasks;
namespace Microsoft.Coyote.Specifications
{
///
/// A monitor that checks if a task eventually completes execution successfully.
///
internal sealed class TaskLivenessMonitor
{
///
/// The task being monitored.
///
private readonly Task Task;
///
/// A counter that increases in each step of the execution, as long as the property
/// has not been satisfied. If the temperature reaches the specified limit, then
/// a potential liveness bug has been found.
///
private int LivenessTemperature;
///
/// True if the liveness property is satisfied, else false.
///
internal bool IsSatisfied => this.Task.Status is TaskStatus.RanToCompletion;
///
/// Trace used for debugging purposes.
///
internal StackTrace StackTrace { get; private set; }
///
/// Initializes a new instance of the class.
///
internal TaskLivenessMonitor(Task task)
{
this.Task = task;
this.LivenessTemperature = 0;
this.StackTrace = new StackTrace();
}
///
/// Checks the liveness temperature of the monitor and report a potential liveness bug if the
/// the value exceeded the specified threshold.
///
internal bool IsLivenessThresholdExceeded(int threshold)
{
if (!this.IsSatisfied && threshold > 0)
{
this.LivenessTemperature++;
if (this.LivenessTemperature > threshold)
{
return true;
}
}
return false;
}
}
}