最近我的winform项目突然遇到一个很奇怪的问题 引发的异常:“System.InvalidOperationException”(位于 System.Windows.Forms.dll 中)
把相关可能的页面都加了try catch,但是依旧找不到异常位置所在。后来同事说断点一步步调试看看,后来终于找到了问题所在
在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。
2023/9/1 10:44:38 在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。
找到问题所在后,我在相关位置加上句柄是否创建的判断,代码如下:
try
{
uiDelegate d = new uiDelegate(HandleMessage);
if (this.IsHandleCreated)
{
this.BeginInvoke(d, new object[] { e });
}
else {
}
}
catch (Exception ex)
{
Logger.Write("Control.MainService_OnServiceMessage 异常 " + ex.Message);
Logger.Write(ex.Message);
}
至此为题得以解决,在此记录以下,以后写代码还是要多注意,要习惯加try catch,定位不到问题时一定要先断点调试。
希望对遇到同样问题的小伙伴有所帮助。