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.