简体   繁体   中英

TargetInvocationException was unhandled - c#

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

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.

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 .

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;
        }
      }
    }

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM