Windows system hangs after few seconds

Hello everyone, i am learning 2D game development from scratch by monogame framework. When i try to run the game, it runs successfully and i am able to see game space. But after 10-20 seconds visual studio stops responding and my system hangs.
I donot have great configurations to build a powerful game but also its not that much weak.

System Specifiactions -
Processor - AMD A4-6210 APU with AMD Radeon R3 Graphics 1.80GHz
RAM - 4GB DDR4

It can be my systems specification or my code stopping me. Somebody have solution?

Im guessing you are on win10 which template are you trying to run ?

.
Also to be clear.
.

Are you following the instructions in the documentation ?

Setting up

Do you follow this as per the next part of the instructions.

This is the link for the most up to date build atm Nightly build

if you get this window you have a successful run or is this what is locking up ?

Hi WillMotil, i am using “MonoGame Windows Project” Template and and developing on Windows 10…
And yes i am also using the setting up instructions.
I also created a game from one of the tutorial on web and it worked fine for me.
I am getting correct o/p but not able to hold at their.

yes i am also using the setting up instructions.

A game 1 class

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Game1
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }
        protected override void Initialize()
        {
            base.Initialize();
        }
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
        }
        protected override void UnloadContent()
        {
        }
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
            base.Update(gameTime);
        }
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            base.Draw(gameTime);
        }
    }
}

I also created a game from one of the tutorial on web and it worked fine for me.

The image you are posting appears to show that you running a monogame app however i see no borders or title window and you appear to be drawing two textures and clearing the background to black.

Previously you stated the problem

But after 10-20 seconds visual studio stops responding and my system hangs.

You asked the question.

can it be my systems specification or my code causing the problem.

By what you are showing it appears that it is your code, which you have added to game1.
There is insufficient information to answer. You would need to post your game1 code i think.
In order for others to attempt to diagnose what exactly that problem stems from.

I am getting correct o/p but not able to hold at their.

I don’t understand what you mean in/by the above sentence. It must be a bad translation for that line.

Here is my Game1.cs -
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Tanks
{
///


/// This is the main type for your game.
///

public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Color backgroundColor = Color.DarkGray;

    GameContent gameContent; // Creating game content object

    private Tank tank;
    private Bricks bricks;
    private Eagle eagle;
    private int screenWidth = 0;
    private int screenHeight = 0;

    // Controls
    private MouseState oldMouseState;
    private KeyboardState oldKeyboardState;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        // TODO: use this.Content to load your game content here
        gameContent = new GameContent(Content);

        
        
        // Getting Screen Width and Height from GraphicsAdapter.DefaultAdapter.CurrentDisplayMode
        screenWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
        screenHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
        //Console.WriteLine("---- Height : "+screenHeight);
        //Console.WriteLine("---- Width : " + screenWidth);

        // Setting Height
        graphics.PreferredBackBufferWidth = screenWidth;
        graphics.PreferredBackBufferHeight = screenHeight;
        graphics.ApplyChanges();

        //create game objects
        
        // Tank
        int tankX = (screenWidth) / 2; //we'll center the tank on the screen to start
        int tankY = screenHeight/2;  //paddle will be 100 pixels from the bottom of the screen
        tank = new Tank(tankX, tankY, screenWidth, spriteBatch, gameContent);  // create the game paddle
        
        // Bricks
        int bricksX = (screenWidth) / 2;
        int bricksy = (screenHeight) / 2;
        bricks = new Bricks(bricksX, bricksy, Color.White, spriteBatch, gameContent);

        // Eagle
        eagle = new Eagle(bricksX, bricksy, Color.White, spriteBatch, gameContent);
    }

    
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        // TODO: Add your update logic here
        KeyboardState newKeyboardState = Keyboard.GetState();
        MouseState newMouseState = Mouse.GetState();

        // Process keyboard events                           
        if (newKeyboardState.IsKeyDown(Keys.Left))
        {
            tank.MoveLeft();
        }
        if (newKeyboardState.IsKeyDown(Keys.Right))
        {
            tank.MoveRight();
        }
        if (newKeyboardState.IsKeyDown(Keys.Up))
        {
            tank.MoveUp();
        }
        if (newKeyboardState.IsKeyDown(Keys.Down))
        {
            tank.MoveDown();
        }


        oldMouseState = newMouseState; // this saves the old state      
        oldKeyboardState = newKeyboardState;

        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here
        spriteBatch.Begin();
        GraphicsDevice.Clear(backgroundColor);

        
        // Creating Gamespace
        Texture2D rect = new Texture2D(graphics.GraphicsDevice, 1000, 650);

        Color[] data = new Color[1000 * 650];
        for (int i = 0; i < data.Length; ++i) data[i] = Color.White;
        rect.SetData(data);

        Vector2 coor = new Vector2(110, 30);
        spriteBatch.Draw(rect, coor, Color.Black);
        //--------------------
        bricks.Draw();
        tank.Draw();
        eagle.Draw();
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

}

**My Problem is - **
If i continuously test my o/p on monogame output window for 10-20 secs, my system hangs and visual studio stops responding.,

In your Draw, you are creating new Texture and setting color data in every frame.That is not what you want to do, it creates tons of garbage memory… Do this just once/when needed.

public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Texture2D whitePixel;
    Rectangle rect = new Rectangle(100, 100, 100, 100);
}

protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(GraphicsDevice);
    whitePixel = new Texture2D(GraphicsDevice, 1, 1);
    whitePixel.SetData<Color>(new Color[1] { Color.White });
}

 protected override void Draw(GameTime gameTime)
 {
    GraphicsDevice.Clear(Color.CornflowerBlue);

    spriteBatch.Begin();
    spriteBatch.Draw(whitePixel, rect, Color.Red);
    spriteBatch.End();

    base.Draw(gameTime);
}
2 Likes

While he is correct that is bad.

That is not the actual source of the problem for the hang.

these lines here are in misuse.

        // Error source.
        // Setting Height
        graphics.PreferredBackBufferWidth = screenWidth;
        graphics.PreferredBackBufferHeight = screenHeight;
        graphics.ApplyChanges();

tested. for failure,

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace TestingGuysFreezeup
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Color backgroundColor = Color.DarkGray;

        // questionable
        GameContent gameContent; // Creating game content object

        private Tank tank;
        private Bricks bricks;
        private Eagle eagle;
        private int screenWidth = 0;
        private int screenHeight = 0;

        // Controls
        private MouseState oldMouseState;
        private KeyboardState oldKeyboardState;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            gameContent = new GameContent(Content);



            // Getting Screen Width and Height from GraphicsAdapter.DefaultAdapter.CurrentDisplayMode
            screenWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
            screenHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
            //Console.WriteLine("---- Height : "+screenHeight);
            //Console.WriteLine("---- Width : " + screenWidth);

            //  !!!!!!!! Error source. !!!!!!!!
            //
            // Setting Height
            //graphics.PreferredBackBufferWidth = screenWidth;
            //graphics.PreferredBackBufferHeight = screenHeight;
            //graphics.ApplyChanges();

            //create game objects

            // Tank
            int tankX = (screenWidth) / 2; //we'll center the tank on the screen to start
            int tankY = screenHeight / 2;  //paddle will be 100 pixels from the bottom of the screen
            tank = new Tank(tankX, tankY, screenWidth, spriteBatch, gameContent);  // create the game paddle

            // Bricks
            int bricksX = (screenWidth) / 2;
            int bricksy = (screenHeight) / 2;
            bricks = new Bricks(bricksX, bricksy, Color.White, spriteBatch, gameContent);

            // Eagle
            eagle = new Eagle(bricksX, bricksy, Color.White, spriteBatch, gameContent);
        }


        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            // TODO: Add your update logic here
            KeyboardState newKeyboardState = Keyboard.GetState();
            MouseState newMouseState = Mouse.GetState();

            // Process keyboard events                           
            if (newKeyboardState.IsKeyDown(Keys.Left))
            {
                tank.MoveLeft();
            }
            if (newKeyboardState.IsKeyDown(Keys.Right))
            {
                tank.MoveRight();
            }
            if (newKeyboardState.IsKeyDown(Keys.Up))
            {
                tank.MoveUp();
            }
            if (newKeyboardState.IsKeyDown(Keys.Down))
            {
                tank.MoveDown();
            }


            oldMouseState = newMouseState; // this saves the old state      
            oldKeyboardState = newKeyboardState;

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            spriteBatch.Begin();
            GraphicsDevice.Clear(backgroundColor);

            // not the source of the problem though this is improper in very very expensive way and will slow the frame rate needlessly in this case.
            // Creating Gamespace
            Texture2D rect = new Texture2D(graphics.GraphicsDevice, 1000, 650);

            Color[] data = new Color[1000 * 650];
            for (int i = 0; i < data.Length; ++i) data[i] = Color.White;
            rect.SetData(data);

            Vector2 coor = new Vector2(110, 30);
            spriteBatch.Draw(rect, coor, Color.Black);
            //--------------------
            bricks.Draw();
            tank.Draw();
            eagle.Draw();
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }

    public class GameContent
    {
        Microsoft.Xna.Framework.Content.ContentManager content;
        public GameContent(Microsoft.Xna.Framework.Content.ContentManager content)
        {
            this.content = content;
        }
        
    }

    public class Tank
    {
        public Tank(int tankX, int tankY, int screenWidth, SpriteBatch spriteBatch, GameContent gameContent)
        {

        }
        public void MoveLeft() { }
        public void MoveRight() { }
        public void MoveUp() { }
        public void MoveDown() { }
        public void Draw() { }
    }
    public class Bricks
    {
        public Bricks(int tankX, int tankY, Color color, SpriteBatch spriteBatch, GameContent gameContent)
        {

        }
        public void Draw() { }
    }
    public class Eagle
    {
        public Eagle(int tankX, int tankY, Color color, SpriteBatch spriteBatch, GameContent gameContent)
        {

        }
        public void Draw() { }
    }
}

The preffered settings are typically placed into a method.
Then called via a key press or when some condition occurs from the update method.

typically these calls are used when in or entering full screen.

To simply resize the window is much easier with a single call in the constructor,
See below.

Minor edit to ManuallyChangeTheBackBuffer and to remove what the other above poster already pointed out into a method, I probably should still test everything for typos never know when someone will take pesudo code for gospel… ok.

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Game1 //Test5
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Color backgroundColor = Color.DarkGray;

        Texture2D rect;

        // this is probably not required i do something similar its fine i guess.
        GameContent gameContent; // Creating game content object

        private Tank tank;
        private Bricks bricks;
        private Eagle eagle;
        private int screenWidth = 1000;
        private int screenHeight = 800;

        // Controls
        private MouseState oldMouseState;
        private KeyboardState oldKeyboardState;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            graphics.PreferredBackBufferWidth = screenWidth;
            graphics.PreferredBackBufferHeight = screenHeight;

            this.IsMouseVisible = true;
            Window.AllowUserResizing = true;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // one time creation this should also be disposed in unload now.
            rect = GetSetDataCreatedTexture(graphics, 1000, 650);

            // TODO: use this.Content to load your game content here
            gameContent = new GameContent(Content);

            // update screen width and height when you resize the window this goes with AllowUserResizing.
            Window.ClientSizeChanged += CallMeWhenTheUserResizesTheWindowHimself;

            // Getting Screen Width and Height from GraphicsAdapter.DefaultAdapter.CurrentDisplayMode
            screenWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
            screenHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;

            //create game objects

            // Tank
            int tankX = (screenWidth) / 2; //we'll center the tank on the screen to start
            int tankY = screenHeight / 2;  //paddle will be 100 pixels from the bottom of the screen
            tank = new Tank(tankX, tankY, screenWidth, spriteBatch, gameContent);  // create the game paddle

            // Bricks
            int bricksX = (screenWidth) / 2;
            int bricksy = (screenHeight) / 2;
            bricks = new Bricks(bricksX, bricksy, Color.White, spriteBatch, gameContent);

            // Eagle
            eagle = new Eagle(bricksX, bricksy, Color.White, spriteBatch, gameContent);
        }

        // this is chained to the callback Window.ClientSizeChanged
        public void CallMeWhenTheUserResizesTheWindowHimself(object sender, EventArgs e)
        {
            screenWidth = GraphicsDevice.Viewport.Width;
            screenHeight = GraphicsDevice.Viewport.Height;
            Console.WriteLine("---- Height : " + screenHeight);
            Console.WriteLine("---- Width : " + screenWidth);
        }

        // if you must set this from a specific need once conditionally from update.
        // calling this everyframe will also lock or crash your app.
        public void ManuallyChangeTheBackBuffer(int width, int height)
        {
            graphics.PreferredBackBufferWidth = width;
            graphics.PreferredBackBufferHeight = height;
            graphics.ApplyChanges();
            screenWidth = GraphicsDevice.Viewport.Width;
            screenHeight = GraphicsDevice.Viewport.Height;
            Console.WriteLine("---- viewport screenHeight : " + screenHeight);
            Console.WriteLine("---- viewport  screenWidth : " + screenWidth);
            Console.WriteLine("---- BackBufferHeight : " + GraphicsDevice.PresentationParameters.BackBufferHeight);
            Console.WriteLine("---- BackBufferWidth : " + GraphicsDevice.PresentationParameters.BackBufferWidth);
            Console.WriteLine("---- CurrentDisplayMode Height : " + GraphicsDevice.Adapter.CurrentDisplayMode.Width);
            Console.WriteLine("---- CurrentDisplayMode  Width : " + GraphicsDevice.Adapter.CurrentDisplayMode.Height);
        }

        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
            if (rect != null)
                if (rect.IsDisposed != true)
                    rect.Dispose();
        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            // TODO: Add your update logic here
            KeyboardState newKeyboardState = Keyboard.GetState();
            MouseState newMouseState = Mouse.GetState();

            // Process keyboard events                           
            if (newKeyboardState.IsKeyDown(Keys.Left))
            {
                tank.MoveLeft();
            }
            if (newKeyboardState.IsKeyDown(Keys.Right))
            {
                tank.MoveRight();
            }
            if (newKeyboardState.IsKeyDown(Keys.Up))
            {
                tank.MoveUp();
            }
            if (newKeyboardState.IsKeyDown(Keys.Down))
            {
                tank.MoveDown();
            }

            if (newKeyboardState.IsKeyDown(Keys.D1))
                ManuallyChangeTheBackBuffer(500, 500);

            oldMouseState = newMouseState; // this saves the old state      
            oldKeyboardState = newKeyboardState;

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            spriteBatch.Begin();
            GraphicsDevice.Clear(backgroundColor);

            Vector2 coor = new Vector2(110, 30);
            spriteBatch.Draw(rect, coor, Color.Black);
            //--------------------
            bricks.Draw();
            tank.Draw();
            eagle.Draw();
            spriteBatch.End();

            base.Draw(gameTime);
        }

        public Texture2D GetSetDataCreatedTexture(GraphicsDeviceManager graphics, int w, int h)
        {
            Texture2D t = new Texture2D(graphics.GraphicsDevice, w, h);
            Color[] data = new Color[w * h];
            for (int i = 0; i < data.Length; ++i) data[i] = Color.White;
            t.SetData(data);
            return t;
        }

        public class GameContent
        {
            Microsoft.Xna.Framework.Content.ContentManager content;
            public GameContent(Microsoft.Xna.Framework.Content.ContentManager content)
            {
                this.content = content;
            }

        }

        public class Tank
        {
            public Tank(int tankX, int tankY, int screenWidth, SpriteBatch spriteBatch, GameContent gameContent)
            {

            }
            public void MoveLeft() { }
            public void MoveRight() { }
            public void MoveUp() { }
            public void MoveDown() { }
            public void Draw() { }
        }
        public class Bricks
        {
            public Bricks(int tankX, int tankY, Color color, SpriteBatch spriteBatch, GameContent gameContent)
            {

            }
            public void Draw() { }
        }
        public class Eagle
        {
            public Eagle(int tankX, int tankY, Color color, SpriteBatch spriteBatch, GameContent gameContent)
            {

            }
            public void Draw() { }
        }
    }
}

While i do not know the specifics of the other classes you did not post. I will hope they are not also hanging your program. if they are re-post and show those as well. I probably need to goto sleep someone else will help probably chime in to help if you still need advice.

Your organization is pretty good for a beginner be-careful however of your namings. rect is a bad name for a texture Type. Especially since there is a Rectangle class that you can feed into draw. As you continue on you will start to notice what i mean when a bad name causes you a bug or causes you confusion.

Names you pick should not only be unique they should convey a purpose to you yourself as a user of them.
So that they convey a idea of a served purpose to you as a tool when you see them.

1 Like

Thanks Tunkio and WillMotil. The code is working fine now.
Will post again, if needed!
Thanks again WillMotil