我使用这个gamedev.stackexchange线程讨论的游戏循环时: https://gamedev.stackexchange.com/questions/67651/what-is-the-standard-c-windows-forms-game-loop代码优化导致空引用异常使用的PeekMessage
一切是伟大的工作,如果我使用调试版本类型,但是当我去要做Release,我得到一个空引用异常。看起来只有在启用代码优化时才会发生。这是做同样事情的准系统例子。该表格完全是空白的,在这个例子中没有按钮/控件。
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Sharp8
{
public partial class DebugForm : Form
{
public DebugForm()
{
InitializeComponent();
Application.Idle += GameLoop;
}
private void GameLoop(object sender, EventArgs e)
{
while (IsApplicationIdle())
{
Console.WriteLine("Game Updates/Rendering!");
}
}
[StructLayout(LayoutKind.Sequential)]
public struct NativeMessage
{
public IntPtr Handle;
public uint Message;
public IntPtr WParameter;
public IntPtr LParameter;
public uint Time;
public Point Location;
}
[DllImport("user32.dll")]
static extern bool PeekMessage(out Message message, IntPtr window, uint messageFilterMinimum, uint messageFilterMaximum, uint shouldRemoveMessage);
private bool IsApplicationIdle()
{
Message result;
return !PeekMessage(out result, IntPtr.Zero, 0, 0, 0);
}
}
}
当我运行此,异常据说里面forms.dll外部代码的情况发生,这是我的Application.Run(“ETC”),启动此表后应丢弃。堆栈跟踪并不是很有用,它只是Application.Run和一堆外部代码。
我不确定是什么造成了这种情况,但我知道它与调用PeekMessage有关,因为如果我将订阅注释到Idle事件中,错误不会发生。
作为一个问题,为什么我需要在这里声明“NativeMessage”结构?如果我把它切掉,它似乎不会引起问题,但每个使用这个游戏循环的例子都包含它。
你能否将代码缩减为一个可展示行为的简短可编译示例? –
完成,这是我所说的最简单的例子。 Console.WriteLine是我的模拟器更新/渲染的地方。 – ALLCAPS