0

I'm trying to create a simple game loop in .NET 5 windows forms application. I just have an empty while but it takes around 14 percent CPU (My CPU is 6 cores so it actually almost blocks an entire core) I created a simple sample. Here is my code

    [StructLayout(LayoutKind.Sequential)]
    public struct NativeMessage
    {
        public IntPtr Handle;
        public uint Message;
        public IntPtr WParameter;
        public IntPtr LParameter;
        public uint Time;
        public System.Drawing.Point Location;
    }

    [DllImport("user32.dll")]
    public static extern int PeekMessage(out NativeMessage message, IntPtr window, uint filterMin, uint filterMax, uint remove);


    static bool IsApplicationIdle()
    {
        NativeMessage result;
        return PeekMessage(out result, IntPtr.Zero, (uint)0, (uint)0, (uint)0) == 0;
    }

    public Form1()
    {
        InitializeComponent();
        Application.Idle += Application_Idle1;
    }

    private static void Application_Idle1(object sender, EventArgs e)
    {
        while (IsApplicationIdle())
        {

        }
    }

As you can see it's just an empty while loop inside application idle event.

KooKoo
  • 451
  • 3
  • 20
  • Imagine a kid asking the driver of the car, are we there yet, are we there yet... many thousands of times a second, constantly and without fail... do you think that is going to use up the drivers time? – TheGeneral Oct 14 '21 at 04:42
  • The linked as duplicate https://stackoverflow.com/questions/4911397/what-is-a-busy-loop explains the code ("busy loop" / "busy wait") you wrote - the concept is the same even if that answer is in C++ instead of C#. There is probably more C# specific explanations - feel free to check search https://www.bing.com/search?&q=what+is+busy+loop%20site:stackoverflow.com and see other questions. If the explanation in the linked question is not enough please [edit] the question to clarify what part you need help understanding. – Alexei Levenkov Oct 14 '21 at 04:47

0 Answers0