From Friday, April 19th (11:00 PM CDT) through Saturday, April 20th (2:00 PM CDT), 2024, ni.com will undergo system upgrades that may result in temporary service interruption.
We appreciate your patience as we improve our online experience.
So I have a set of code I've posted multiple times on the forums for displaying images using the .NET picture box. I then started losing my mind when things stopped working the way I wanted. I rolled back my software and realized this issue has always been there. What I am seeing is if I open and display an image in my picturebox, then close it and reopen the same file, eventually I get a .NET Exception, and I don't know why. The number of times the file can be opened successfully varies but I see around 30 or 40 times, but as few as 5 and as many as 100. Can some tell me what I'm doing wrong? I thought I had a set of stable good code and now I'm seeing I don't.
Attached is the code. Run Open In a Loop and run it. It should display an image and at some point I get an error and the image is no longer displayed.
See the end of this message for details on invoking just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text ************** System.ArgumentException: Parameter is not valid. at System.Drawing.Image.get_Width() at System.Drawing.Image.get_Size() at System.Windows.Forms.PictureBox.ImageRectangleFromSizeMode(PictureBoxSizeMode mode) at System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe) at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer) at System.Windows.Forms.Control.WmPaint(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ActiveXImpl.System.Windows.Forms.IWindowTarget.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
************** JIT Debugging ************** To enable just-in-time (JIT) debugging, the .config file for this application or computer (machine.config) must have the jitDebugging value set in the system.windows.forms section. The application must also be compiled with debugging enabled.
For example:
<configuration>
My first suspicion is I'm not closing or disposing of a reference properly but throwing dispose and close in random places doesn't seem to be helping. Thanks.
Okay with some help from here, I think I know what my problem is. At the end I'm disposing of an image, that is referenced by the picture box. I shouldn't dispose of the image, until there is something (anything) in the picture box instead. So I read the image, I write a new image that is a null, then dispose of the old image. An alternative would be to try to get a new copy of the image and then disposing of the old one but that didn't work for some reason.