I have implemented a game engine loop as follows:
public static Boolean Start ( )
{
if (hasBoard)
{
// start engine on worker thread
asyncTask = new AsyncResult ( stopEngine, asyncTask );
isRunning = ThreadPool.QueueUserWorkItem ( startEngine, asyncTask );
if (isRunning)
{
Console.WriteLine ( "[{0}] Engine started",
DateTime.Now.ToString ( "hh:mm:ss" ) );
}
else
{
Console.WriteLine ( "[{0}] Engine failed to start",
DateTime.Now.ToString ( "hh:mm:ss" ) );
}
}
return isRunning;
}
public static void Stop ( )
{
Console.WriteLine ( "[{0}] Engine stopping",
DateTime.Now.ToString ( "hh:mm:ss" ) );
asyncTask.SetAsCompleted ( null, false );
}
private static void startEngine ( Object task )
{
while (!( (IAsyncResult)task ).IsCompleted)
{
Thread.Sleep ( 10000 );
Console.WriteLine ( "[{0}] Engine running",
DateTime.Now.ToString ( "hh:mm:ss" ) );
}
}
private static void stopEngine ( IAsyncResult iaResult )
{
// clean up resources
Console.WriteLine ( "[{0}] Engine stopped",
DateTime.Now.ToString ( "hh:mm:ss" ) );
isRunning = false;
}
I am using the AsyncResult
class recommended by Jeff Richter in his article, Implementing the CLR Asynchronous Programming Model. In order to be able to stop the engine from the UI, the implementation I used was a bit off from the standard asynchronous pattern. This implementation works as expected, but when I divert from a standard practice, I revert to the SO community to ensure I am doing things the right way.
Are there any issues with this implementation that anyone can see?