using System;
using System.Diagnostics;
namespace grof{
/// <summary>
/// Each message which is sent by a group
/// member holds a timestamp value. This class
/// helps for calculating the right timestamp value.
/// </summary>
public class TimeStamp
{
/// <summary>
/// The difference between two
/// <c>DateTime</c> values.
/// </summary>
private TimeSpan timeSpan = TimeSpan.Zero;
/// <summary>
/// Constructor.
/// </summary>
public TimeStamp()
{
}
// TODO: unit test this class
/// <summary>
/// If the local group member receives a JOIN or
/// ALIVE message from another group member it retrieves
/// the timestamp from the received message and passes the
/// value to the <c>CheckAndSetTimeStamp</c> method. This method
/// compares the timestamp of the received message with the local
/// timestamp. If the 'remote' timestamp is higher than the local
/// timestamp, the local timestamp value is set to the value of
/// the 'remote' timestamp.
/// </summary>
/// <param name="timeStamp">The timestamp value of received messages.</param>
public void CheckAndSetTimeStamp( long timeStamp )
{
lock( this )
{
DateTime remoteTime = DateTime.FromBinary( timeStamp );
DateTime localTime = DateTime.Now + this.timeSpan;
Debug.WriteLine( "[TimeStamp#CheckAndSetTimeStamp] local time: " + localTime );
Debug.WriteLine( "[TimeStamp#CheckAndSetTimeStamp] remote time: " + remoteTime );
if ( remoteTime > localTime )
{
TimeSpan timeDiff = remoteTime - localTime;
this.timeSpan = this.timeSpan + timeDiff;
Debug.WriteLine( "[TimeStamp#CheckAndSetTimeStamp] new local time: " +
(DateTime.Now + this.timeSpan) );
}
}
}
/// <summary>
/// Returns the current timestamp value.
/// </summary>
/// <returns>The current timestamp value.</returns>
public long GetTimeStamp()
{
lock( this )
{
return ( DateTime.Now + this.timeSpan ).ToBinary();
}
}
}
}
|