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

发布于 2024-10-10 03:46:41 字数 1542 浏览 8 评论 0原文

我已经实现了一个游戏引擎循环,如下所示:

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 在他的文章中推荐的 AsyncResult 类,实现 CLR 异步编程模型。为了能够从 UI 停止引擎,我使用的实现与标准异步模式有点不同。这个实现按预期工作,但是当我偏离标准实践时,我会回到 SO 社区以确保我以正确的方式做事。

此实施是否存在任何人都可以看到的问题?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梨涡少年 2024-10-17 03:46:41

由于这听起来像是您可以控制的项目,因此我建议您放弃 APM 并使用 .NET4 中提供的基于 Task 的模型。这是 .NET4 而不是 APM 的推荐方法。 Task 类是任务并行库 (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;
    }
}

Since this sounds like a project you have control over, I would suggest you ditch APM and use the Task-based model provided in .NET4. This is the recommended approach for .NET4 instead of APM. The Task class is part of the Task Parallel Library (TPL) but it's great for these basic asynchronous jobs as well.

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;
    }
}
洛阳烟雨空心柳 2024-10-17 03:46:41

我想说,这意味着使用线程池时任务是短暂的,因为其中的线程数量是有限的。

在你的情况下,因为你提到了winforms,所以我会使用BackgroundWorker。 BW 为您处理同步,因此能够在不使用 InvokeRequired 等的情况下更新 GUI。

I would say that It's implied that tasks are short-lived when using the thread pool since the number of threads in it is limited.

In you case I would use a BackgroundWorker instead since you mentioned winforms. BW handles synchronization for you and are therefore able to update the GUI without using InvokeRequired etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文