增强图像更新异常处理:在UpdatePictureBoxImage方法中添加多层异常捕获机制,包括控件有效性双重检查、图像设置过程异常处理和外层异常捕获,防止在窗口频繁打开关闭时出现System.ArgumentException异常
This commit is contained in:
@@ -89,35 +89,57 @@ namespace JoyD.Windows.CS
|
||||
// 安全更新图像
|
||||
if (pictureBoxTemperatureDisplay != null && !pictureBoxTemperatureDisplay.IsDisposed)
|
||||
{
|
||||
// 保存旧图像引用,以便设置新图像后释放
|
||||
Image oldImage = pictureBoxTemperatureDisplay.Image;
|
||||
|
||||
// 检查mRealTimeImage是否有效 - 只设置有效的图像
|
||||
Image imageToSet = null;
|
||||
try
|
||||
{
|
||||
// 验证图像是否有效(尝试访问图像属性,如果无效会抛出异常)
|
||||
if (mRealTimeImage != null)
|
||||
// 保存旧图像引用,以便设置新图像后释放
|
||||
Image oldImage = pictureBoxTemperatureDisplay.Image;
|
||||
|
||||
// 检查mRealTimeImage是否有效 - 只设置有效的图像
|
||||
Image imageToSet = null;
|
||||
try
|
||||
{
|
||||
// 尝试访问Width属性来验证图像是否有效
|
||||
var width = mRealTimeImage.Width;
|
||||
// 如果没有抛出异常,则图像有效
|
||||
imageToSet = mRealTimeImage;
|
||||
// 验证图像是否有效(尝试访问图像属性,如果无效会抛出异常)
|
||||
if (mRealTimeImage != null)
|
||||
{
|
||||
// 尝试访问Width属性来验证图像是否有效
|
||||
var width = mRealTimeImage.Width;
|
||||
// 如果没有抛出异常,则图像有效
|
||||
imageToSet = mRealTimeImage;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// 图像无效,不设置它
|
||||
// 可以选择记录日志或创建一个默认的错误图像
|
||||
}
|
||||
|
||||
// 再次检查控件是否仍然有效,防止在验证过程中控件被释放
|
||||
if (pictureBoxTemperatureDisplay != null && !pictureBoxTemperatureDisplay.IsDisposed)
|
||||
{
|
||||
// 设置图像(如果有效)
|
||||
try
|
||||
{
|
||||
pictureBoxTemperatureDisplay.Image = imageToSet;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 捕获设置图像时可能发生的异常
|
||||
System.Diagnostics.Debug.WriteLine($"设置PictureBox图像失败: {ex.Message}");
|
||||
// 确保设置为null而不是无效图像
|
||||
pictureBoxTemperatureDisplay.Image = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 释放旧图像(如果不是当前设置的图像)
|
||||
if (oldImage != null && oldImage != imageToSet)
|
||||
{
|
||||
try { oldImage.Dispose(); } catch { }
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 图像无效,不设置它
|
||||
// 可以选择记录日志或创建一个默认的错误图像
|
||||
}
|
||||
|
||||
// 设置图像(如果有效)
|
||||
pictureBoxTemperatureDisplay.Image = imageToSet;
|
||||
|
||||
// 释放旧图像(如果不是当前设置的图像)
|
||||
if (oldImage != null && oldImage != imageToSet)
|
||||
{
|
||||
try { oldImage.Dispose(); } catch { }
|
||||
// 捕获所有其他异常,确保方法不会崩溃
|
||||
System.Diagnostics.Debug.WriteLine($"UpdatePictureBoxImage异常: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user