我实现了一个游戏引擎循环如下:
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;
}
我正在使用 Jeff Richter 在他的文章 Implementing the CLR Asynchronous Programming Model 中推荐的 AsyncResult
类.为了能够从 UI 停止引擎,我使用的实现与标准异步模式有点不同。此实现按预期工作,但当我偏离标准做法时,我会回到 SO 社区以确保我以正确的方式做事。
此实现是否存在任何人都可以看到的问题?
最佳答案
由于这听起来像是您可以控制的项目,我建议您放弃 APM 并使用 .NET4 中提供的基于 Task
的模型。这是 .NET4 而非 APM 的推荐方法。 Task
类是Task Parallel Library ( TPL ) 的一部分,但它也非常适合这些基本的异步作业。
private CancellationTokenSource cts;
public void StartEngine()
{
if (cts == null)
{
cts = new CancellationTokenSource();
Task.Factory.StartNew(() => GameLoop(cts.Token), cts.Token);
}
}
private void GameLoop(CancellationToken token)
{
while (true)
{
token.ThrowIfCancellationRequested();
Thread.Sleep(1000);
Debug.WriteLine("working...");
}
}
public void StopEngine()
{
if (cts != null)
{
cts.Cancel();
cts = null;
}
}
关于c# - 是否有实现异步游戏引擎循环的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4576982/