我已经实现了一个游戏引擎循环,如下所示:
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;
}
我正在使用AsyncResult
Jeff Richter 在他的文章实现 CLR 异步编程模型中推荐的类。为了能够从 UI 中停止引擎,我使用的实现有点偏离标准的异步模式。此实现按预期工作,但是当我偏离标准实践时,我会回到 SO 社区以确保我以正确的方式做事。
此实现是否存在任何人都可以看到的问题?