在尝试分配位图时随机获得异常

本文关键字:随机 异常 位图 分配 | 更新日期: 2023-09-27 18:05:23

我有一个c#应用程序表单,在关闭和打开另一个表单之前显示图像3秒。代码如下:

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace SampleProgram
{
public partial class failureMessage : Form
{
    private Bitmap backgroundImage = null; // backgound image bitmap
    private System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
    private const string imagePath = @"/NandFlash/MsgRefused.png";
    // Constructor
    public failureMessage()
    {
        InitializeComponent();
        this.Height = Screen.PrimaryScreen.Bounds.Height;
        this.Width = Screen.PrimaryScreen.Bounds.Width;
        try
        {
            backgroundImage = new Bitmap(imagePath);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        myTimer.Tick += new EventHandler(TimerEventProcessor);
        // Sets the timer interval to 3 seconds.
        myTimer.Interval = 3000;
        myTimer.Enabled = true;
    }
    #region Timer event
    // This is the method to run when the timer is raised. 
    private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
    {
        myTimer.Enabled = false;
        myTimer.Dispose();
        backgroundImage.Dispose();
        backgroundImage = null;
        Form1 reopenMainpage = new Form1();
        reopenMainpage.Show();
        this.Close();
    }
    #endregion
    #region Paint the background
    protected override void OnPaintBackground(PaintEventArgs e)
    {
        e.Graphics.DrawImage(backgroundImage, 0, 0);
    }
    #endregion
}
}

然而,在随机的情况下,我一直得到以下异常:

System.Exception was unhandled
Message="Exception"
StackTrace:
Location: Microsoft.AGL.Common.MISC.HandleAr(PAL_ERROR ar)
Location: System.Drawing.Bitmap._InitFromMemoryStream(MemoryStream mstream)
Location: System.Drawing.Bitmap..ctor(String filename)
Location: SampleProgram.failureMessage..ctor()
Location: SampleProgram.Form1.ReceivedMsg(Object sender, FingerPrintSensorEventArgs e)
Location: SG7000.device.WndProcModification.onFGSensorTriggered(FingerPrintSensorEventArgs e)
Location: SG7000.device.WndProcModification.MyWndProc(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam)
Location: Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr hwnMain)
Location: System.Windows.Forms.Application.Run(Form fm)
Location: SampleProgram.Program.Main()

在一些研究,我怀疑这可能是我没有处置位图对象或定时器对象之前关闭的形式,但错误仍然是随机时间。是我的实现有问题,还是我忘了做什么?任何建议都很感激。由于

在尝试分配位图时随机获得异常

堆栈跟踪显示在初始化位图时发生异常。一个解决方法是不抛出异常。

    try
    {
        backgroundImage = new Bitmap(imagePath);
    }
    catch (Exception ex)
    {
        // Don't throw
    }

如果你经常加载位图,我建议将图片移动到资源中,并从那里访问它。

同样,将下面的行移动到Close事件处理程序。将处理程序附加到Close事件。这将确保在窗体关闭时所有内容都被处理掉。

myTimer.Enabled = false;
myTimer.Dispose();
backgroundImage.Dispose();
backgroundImage = null;