Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there best practices for implementing an asynchronous game engine loop?

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?

like image 620
IAbstract Avatar asked Jan 02 '11 03:01

IAbstract


People also ask

What is game loop explain different steps and methods involved in the main loop?

A game loop runs continuously during gameplay. Each turn of the loop, it processes user input without blocking, updates the game state, and renders the game. It tracks the passage of time to control the rate of gameplay. This pattern decouples progression of game time from user input and processor speed.

How often does a game loop typically run?

Most real-time games update several times per second: 30 and 60 are the two most common intervals. If a game runs at 60 FPS (frames per second), this means that the game loop completes 60 iterations every second.

Does every game have a game loop?

Game loops are the quintessential example of a “game programming pattern”. Almost every game has one, no two are exactly alike, and relatively few programs outside of games use them. To see how they're useful, let's take a quick trip down memory lane.


2 Answers

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;
    }
}
like image 108
Rick Sladkey Avatar answered Sep 27 '22 20:09

Rick Sladkey


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.

like image 42
jgauffin Avatar answered Sep 27 '22 21:09

jgauffin