Thursday, July 21, 2016

.NET Reflection bug

Had a fun bug with an app the other day. I had been leaving the app to run for a long time so I could monitor memory usage to check for any possible leaks. But the following bug was reported after a couple of hours:

“target invocation exception” in System.Reflection

 at the following line

this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));

but that line was in the form.designer.cs generated by Visual Studio and you would assume that this code was only executed when the form was first rendered.

I was potentially fighting an abstraction then – clearly one that had leaked

Then I remembered that the program updated the task bar icon to alert its user to potentially new and interesting occurrences. I had made sense at the time of writing to make use of the icon stored as a resource associated with the form. The image was retrieved using:

Bitmap b = this.Icon.ToBitmap();

then decorated and set as a revised taskbar icon – which is (of course) also the current form icon which just might give some insight into what was going wrong or at least a faint hint.

The icon file itself was properly formatted and contained 16x16 and 32x32 pixel bitmaps but it was clear that somewhere along the line and after several successful invocations in each instance something went wrong in mscorlib and the debug facility in Visual Studio pinned the problem back on the partial (designer) class for the form.

A couple of solutions came to mind but I went with embedding a 32x32 .png image as an additional assembly resource and retrieving that when it was required. So far, that has yet to fail but yes, there is a small memory leak somewhere so I am not finished yet. Testing and modifying programs designed to run continuously for extended periods within a Windows environment can be a challenge.