public static bool ToStopping(ref ForwardedPortStatus status)
{
// attempt to transition from Started to Stopping
var previousStatus = Interlocked.CompareExchange(ref status, Stopping, Started);
if (previousStatus == Stopping || previousStatus == Stopped)
{
// status is already Stopping or Stopped, so no transition to Stopping is necessary
return false;
}
// we've successfully transitioned from Started to Stopping
if (status == Stopping)
return true;
// attempt to transition from Starting to Stopping
previousStatus = Interlocked.CompareExchange(ref status, Stopping, Starting);
if (previousStatus == Stopping || previousStatus == Stopped)
{
// status is already Stopping or Stopped, so no transition to Stopping is necessary
return false;
}
// we've successfully transitioned from Starting to Stopping
if (status == Stopping)
return true;
// there's no valid transition from status to Stopping
throw new InvalidOperationException(string.Format("Forwarded port cannot transition from '{0}' to '{1}'.",
previousStatus,
Stopping));
}