5

i really can't figure out what's happening and why it keeps happening
Exception has been thrown by the target of an invocation.

the code was running in the frm5

then the error shows at
Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace BlueStitch
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmMain());
        }
    }
}  

it was in the line Application.Run(new frmMain());

it says TargetInvocationException was unhandled - Exception has been thrown by the target of an invocation.

this the exception

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: Parameter is not valid.
at System.Drawing.Image.get_FrameDimensionsList()
at System.Drawing.ImageAnimator.CanAnimate(Image image)
at System.Drawing.ImageAnimator.ImageInfo..ctor(Image image)
at System.Drawing.ImageAnimator.Animate(Image image, EventHandler onFrameChangedHandler)
at System.Windows.Forms.PictureBox.Animate(Boolean animate)
at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
at BlueStitch.frmStitch.backgroundWorker1_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e) in C:\Users\Freddie Rosillo\Documents\Visual Studio 2008\Projects\BlueStitch\BlueStitch\BlueStitch\frmStitch.cs:line 976
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at BlueStitch.Program.Main() in C:\Users\Freddie Rosillo\Documents\Visual Studio 2008\Projects\BlueStitch\BlueStitch\BlueStitch\Program.cs:line 21
Ozarraga_AB
  • 939
  • 5
  • 15
  • 24
  • 1
    Please provide a full exception information (including stack trace). – Andrey Shchekin Mar 01 '12 at 02:32
  • Can you provide how are you instantiate `frmStitch` from `frmMain`, you might need to arrange the codings from different events. – Turbot Mar 01 '12 at 04:00
  • Do you have a form called frmMain in the project? – TheHorse1234 Mar 01 '12 at 02:35
  • Did you ever solve this one? I have hit the same problem, with an internally-triggered call to `Animate` throwing an exception despite the image not being multi-frame, and despite the fact that `System.ArgumentException` is never thrown by `System.Drawing.Image.get_FrameDimensionsList`. – tcarvin Sep 27 '13 at 19:12

5 Answers5

3

You are executing some code inside your frmMain constructor that shouldn't be executed there. Move that code and execute it on Form Shown event.

Aleksandar Vucetic
  • 14,715
  • 9
  • 53
  • 56
2

It looks as though you're using a BackgroundWorker to do some work on a background thread. Check that you're not doing anything that must be done on the UI thread. Does the problem go away if you temporarily change the code to perform the work synchronously?

Note that ArgumentException is thrown by the COM method under various circumstances. The source for SafeNativeMethods.Gdip.StatusException does potentially throw ArgumentException, if the argument is 2, 13, 14, 15, 16, 19 or 20. There are a couple of other posts about similar problems here and here.

Community
  • 1
  • 1
Olly
  • 5,966
  • 31
  • 60
  • I have the same exception as the original poster, but *not* from a BackgroundWorker callback. No threads involved at all actually. Therefore I don't think it is directly related to threading. – tcarvin Oct 07 '13 at 11:50
  • Could you try and isolate the minimal amount of code needed to reproduce the error? The stack trace doesn't give us much to go on! – Olly Oct 07 '13 at 13:01
  • I'm not the original poster, but I had a similar exception stack to his, starting at `System.Windows.Forms.PictureBox.Animate(Boolean animate)` with the `ArgumentException` in `get_FrameDimensionsList`. If you look at the code posted by @StevenP, that method shouldn't ever even throw that exception. All of these methods are private or internal to the .NET Framework. – tcarvin Oct 07 '13 at 13:06
  • What I find interesting is that the OP triggered this behavior by chaning the visibility of a PictreBox (see `System.Windows.Forms.Control.SetVisibleCore(Boolean value)` in the call stack. I did this by changing the enabled state. Using reflector, both seem to causing the `Animate` method to be run. Though in my case, the image is not a multi-frame image at all, so I don't know why it is going down that path. – tcarvin Oct 07 '13 at 13:08
  • 1
    @tcarvin - if you look at the code for `SafeNativeMethods.Gdip.StatusException` it does potentially throw `ArgumentException`, if the argument is 2, 13, 14, 15, 16, 19 or 20. – Olly Oct 07 '13 at 13:18
  • Similar exception reported here: http://stackoverflow.com/questions/17309280/pictureboxs-throws-exception-when-changing-image. – Olly Oct 07 '13 at 13:25
  • Ah, I missed that `SafeNativeMethods.Gdip.StatusException(frameDimensionsCount)` was a static method, due to the preceeding `throw` I though it was some type of internal exception. Looks like "Invalid Parameter" happens on a 2. Very interesting! – tcarvin Oct 07 '13 at 13:30
  • Please move the relevant comments into the answer body, at the moment this has been the most helpful. Unfortunately, in my case the displayed image was not being changed or loaded as in the linked replies, but this is still more forward progress then I had before. – tcarvin Oct 07 '13 at 13:42
2

I'm not much of graphics man, but the failing line:

System.Drawing.Image.get_FrameDimensionsList()

Makes a few GDI+ calls and seems to want certain values for the FrameDimensionsCount of the image... is it animated gifs you're dealing? Or TIFFs?

Check out the docs for GdipImageGetFrameDimensionsCount and see if anything twigs. Decompiled failing getter below:

[Browsable(false)]
    public Guid[] FrameDimensionsList
    {
      get
      {
        int count;
        int frameDimensionsCount = SafeNativeMethods.Gdip.GdipImageGetFrameDimensionsCount(new HandleRef((object) this, this.nativeImage), out count);
        if (frameDimensionsCount != 0)
          throw SafeNativeMethods.Gdip.StatusException(frameDimensionsCount);
        if (count <= 0)
          return new Guid[0];
        int num1 = Marshal.SizeOf(typeof (Guid));
        IntPtr num2 = Marshal.AllocHGlobal(num1 * count);
        if (num2 == IntPtr.Zero)
          throw SafeNativeMethods.Gdip.StatusException(3);
        int frameDimensionsList = SafeNativeMethods.Gdip.GdipImageGetFrameDimensionsList(new HandleRef((object) this, this.nativeImage), num2, count);
        if (frameDimensionsList != 0)
        {
          Marshal.FreeHGlobal(num2);
          throw SafeNativeMethods.Gdip.StatusException(frameDimensionsList);
        }
        else
        {
          Guid[] guidArray = new Guid[count];
          try
          {
            for (int index = 0; index < count; ++index)
              guidArray[index] = (Guid) System.Drawing.UnsafeNativeMethods.PtrToStructure((IntPtr) ((long) num2 + (long) (num1 * index)), typeof (Guid));
          }
          finally
          {
            Marshal.FreeHGlobal(num2);
          }
          return guidArray;
        }
      }
    }
Steven P
  • 1,956
  • 1
  • 16
  • 17
  • I too dumped get_FrameDimensionsList as it is the method that threw the error. I cannot see how this method is even capable of throwing a `System.ArgumentException: Parameter is not valid.` In my situation anyway, with a similar exception stack, the image is not one that has frames or requires an `Animate` (which is the method on the call stack that leads to this one). – tcarvin Oct 07 '13 at 11:47
1

When you try to grab the FrameDimensionsList property from your frmStitch.backgroundWorker1_RunWorkerCompleted method, it cannot find the property, because you are outside the BackgroundWorker thread. RunWorkerCompleted executes code back in the original thread after you have finished your work in the BackgroundWorker thread.

We normally use the BackgroundWorker.ReportProgress method to communicate from the BGW thread to the main thread. To communicate the other way around (which seems to be what you're trying to do), I would consider subscribing to an event in the main thread from the BGW thread, so that the BGW thread can update the relevant property, based on something you're doing in the main thread.

Alternatively, check out this post

Community
  • 1
  • 1
Riegardt Steyn
  • 5,431
  • 2
  • 34
  • 49
  • I have the same exception as the original poster, but not from a BackgroundWorker callback. No threads involved at all actually. Therefore I don't think it is directly related to threading. – tcarvin Oct 07 '13 at 11:50
  • Damn, ok I added a link to a (possibly) related SO question. – Riegardt Steyn Oct 07 '13 at 12:13
  • Thanks for the link on trying to intercept (via the debugger) the throw of the actual (inner) exception when a `TargetInvocationException` is normally thrown. In this case, the inner exception is an `ArgumentException`, and I was hoping to learn why that one would be thrown. But perhaps with the linked SO question I can gain some additional information. – tcarvin Oct 07 '13 at 12:26
1

Every Exception in .NET will fall on the line Application.Run(new frmMain()); because this method runs a message loop and it stays active unless window is closed.

However your Exception is common exception always thrown while playing with Images on GDI+, and GDI has known memory leaks that results in this error which is eventually due to no more memory available error.

I can write more about your error once I can see what you are doing with Images, most likely your memories used for your images are not released which causes this problem. These problems of memory with Images were resolved in WPF, switching to image manipulation on WPF does not cause these errors. You can still use WPF inside .NET Forms to process images without causing memory errors and use Windows Forms as you need.

Akash Kava
  • 39,066
  • 20
  • 121
  • 167
  • Are you saying that a System.ArgumentException: Parameter is not valid thrown from get_FrameDimensionsList is common? Please elaborate. – tcarvin Oct 07 '13 at 11:51
  • So far, your answer is the only one that possibly provides a hint at the underlying cause of the exception. Please elaborate, give examples, or references on getting an `System.ArgumentException` from fairly deep within the WinForms/GDI+ infrastructure. The bounty is expiring and I'd like to award it properly. – tcarvin Oct 07 '13 at 12:31
  • I had same problem, if you look for threads on SO for ASP.NET GDI Plus errors you will get same exception, There is a discussion here regarding same. http://social.msdn.microsoft.com/Forums/vstudio/en-US/6f4d1c8f-a9fd-4696-8b89-541b5692f5f6/bitmap-creation-argumentexception-raised-instead-of-out-of-memory?forum=netfxbcl – Akash Kava Oct 07 '13 at 19:10