c# - 是否有实现异步游戏引擎循环的最佳实践?

标签 c# .net asynchronous game-loop

我实现了一个游戏引擎循环如下:

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/

相关文章:

c# - 在表单中将数据从用户控件 A 传递到用户控件 B

C# 二进制序列化

c# - LINQ聚合算法详解

multithreading - I/O 完成端口 (Windows) 或异步 I/O (AIO) 是否会提高处理大量请求的多线程服务器的性能?

.net - ADO.Net 最佳实践 - 进行异步数据库调用时的单连接与多连接

c# - 为什么画圈后颜色会变?

c# - 使用 NHibernate/CaSTLe ActiveRecord 将枚举映射到数据库

c# - WPF 渲染事件不绘制任何东西

c# - LINQ to Entities 无法识别方法 'System.DateTime GetValueOrDefault()'

docker - 在ubuntu上构建dotnet core 3.0依赖时资源暂时不可用