Search code examples
c#winformsresourcesiconstargetinvocationexception

Instance of AggregateException causes TargetInvocationException


I have a problem that an instance of an AggregateException causes a TargetInvocationException after a couple of accesses to an Icon resource.

I broke down the problem to the following steps to reproduce (.Net 4.0 full or client profile):

  • Create a new WinForms application (a console application will not work)
  • Add an arbitrary icon (.ico file) to the resources
  • Add the following code to the constructor:

    new AggregateException();
    for (var i = 0; ; ++i)
    {
      var icon = Resources.Certificate;
    }
    

You have to change the resource name to the name of your resource.

That's all. Yes I know that this sample doesn't make sense. It's just to illustrate the problem. My working code is much more complex and all of this code is needed.

Without creating this excection the application will work forewer. But if this exception is created the access to the resource will fail with a TargetInvocationException. The InnerException told me that the operation has been finished successfully(?!?!) having a two-line stack trace in System.Drawing.Icon (ctor + Initialize).

What can I do to prevent this problem?

EDIT It seems to be a problem using Windows 7. A binary which fails on Win 7 will run correctly in Win 8.1.


Solution

  • I found the reason for that problem:

    The following system configuration is needed to reproduce the issue:

    • Windows 7 German Edition
    • Microsoft .Net Framework 4.5.2 installed (yes I know my binary is compiled against .Net 4.0)
    • KB2901983 installed

    Having a machine which only contains the .Net Framework without KB2901983 the program works fine. After installing KB2901983 the program fails for the same binary (no recompilation required).

    I tried to uninstall KB2901983 but it doesn't help. If it was once installed the program will fail. I tested it on a clean Windows 7 German Edition.