Friday, January 11, 2008

Brain Twister for the day

Examine this Clock class we wrote for a game we developed.


public class Clock
{

public delegate void TickDelegate();

private int _milliSeconds = 100;
private bool _stop = false;

private Thread _internalThread = null;
private event TickDelegate Ticks;


///
/// Game clock constructor
///

///
private Clock(TickDelegate t)
{
Ticks += t;
}

///
/// The interval
///

private int Interval
{
get
{
return _milliSeconds;
}
set
{
_milliSeconds = value;
}
}

///
/// StartLoop the clock
///

private void StartLoop()
{

_stop = false;
System.Diagnostics.Debug.WriteLine("Worker Thread Id - " + Thread.CurrentThread.ManagedThreadId);
while (!_stop)
{
Thread.Sleep(_milliSeconds);
if (Ticks != null)
Ticks.Invoke();
}
}

///
/// Start the clock
///

public void Start()
{
_internalThread.Start();
}



///
/// Stop the clock
///

public void Stop()
{
_stop = true;
_internalThread.Join();
}

///
/// Inititialize the game clock
///

///
public static Clock CreateClock(TickDelegate t, int interval)
{
Clock g=new Clock(t);
g.Interval = interval;
g._internalThread = new Thread(new ThreadStart(g.StartLoop));
return g;
}

}


Questions:

1 – How a client instantiate this clock, and obtain the clock ticks by registering an event handler?
2 – Why we need to do _internalThread.Join() when we stop the clock?

No comments: