Search code examples
c#game-enginegame-development

Application not launching without part being commented


I am making an engine for my game and I have this bit of code:

protected override void OnLoad(EventArgs e)
{
    GameTime.stopwatch.Start();
    if (GameTime.stopwatch.IsRunning)
    {
        GameTime.CallUpdate();
    }
    base.OnLoad(e);
}

and if I don't comment out either the stopwatch.Start() or the if statement, or if I just have GameTime.CallUpdate(), no application window pops up. It does not matter which I comment out, it just doesn't have a window if both are uncommented. If anyone can help me fix the issue of the app window not launching when I run the code uncommented please let me know.

Edit: Neither CallUpdate and stopwatch are part of LAUNCHING the window, which adds to my confusion

public static void CallUpdate()
{
    Debug.Write("I am here");
    while (stopwatch.IsRunning)
    {
        if (stopwatch.ElapsedMilliseconds > 120)
        {
            timeSinceUpdate = (int)stopwatch.ElapsedMilliseconds;
            Debug.Write("Updated");
            //Call update
            stopwatch.Restart();
        }
    }
}

Solution

  • I recommend looking into the subject of threading in C#. All of the code you provided runs on a single thread which also happens to be the UI thread.

    When you uncomment GameTime.stopwatch.Start();, it makes the value of stopwatch.IsRunning to be always true, so the loop while (stopwatch.IsRunning) runs infinitely. Because of that CallUpdate method never finishes execution and base base.OnLoad(e); is never called and your window never shown.

    A trivial example how to solve this would be using Task.Run, e.g.

    protected override void OnLoad(EventArgs e)
    {
        Task.Run(() => {
            GameTime.stopwatch.Start();
            if (GameTime.stopwatch.IsRunning)
            {
                GameTime.CallUpdate();
            }
        });
        base.OnLoad(e);
    }
    

    This task executes the code inside it asynchronously on another thread and will not block base.OnLoad(e);. However, you still have an infinite loop on that asynchronous thread and you'll have to stop the stopwatch somewhere in order for the CallUpdate method to complete.

    Also, threading, introduces a significant amount of complexity to deal with. For example most platforms require a technique called synchronization when attempting to update a UI element from a non-UI thread.

    Perhaps, using a simple Timer class instead, might be enough in your case. All depends on what you plan to do with your GameTime.