TargetInvocationException未处理 - c#

时间:2012-03-01 02:28:17

标签: c# winforms

我真的无法弄清楚发生了什么以及为什么会一直发生这种情况 调用目标引发了异常。

代码在 frm5

中运行

然后错误显示在
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());
        }
    }
}  

它位于Application.Run(new frmMain());

它说TargetInvocationException was unhandled - Exception has been thrown by the target of an invocation.

这个例外

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

5 个答案:

答案 0 :(得分:3)

您正在执行frmMain构造函数中的一些不应该在那里执行的代码。移动该代码并在Form Shown事件上执行它。

答案 1 :(得分:2)

我不是图形人,但是失败的一行:

  

System.Drawing.Image.get_FrameDimensionsList()

进行一些GDI +调用并且似乎想要图像的FrameDimensionsCount的某些值...它是你正在处理的GIF动画吗?还是TIFF?

查看GdipImageGetFrameDimensionsCount的文档,看看是否有任何树枝。下面的反编译失败的getter:

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

答案 2 :(得分:2)

看起来好像你正在使用BackgroundWorker在后​​台线程上做一些工作。检查您是否在UI线程上没有做任何必须完成的事情。如果您暂时更改代码以同步执行工作,问题是否会消失?

请注意,在各种情况下,COM方法会抛出ArgumentException。如果参数为2,13,14,15,16,19或20,SafeNativeMethods.Gdip.StatusException的来源可能会抛出ArgumentException。还有其他一些关于类似问题的帖子herehere

答案 3 :(得分:1)

当您尝试从 frmStitch.backgroundWorker1_RunWorkerCompleted 方法中获取FrameDimensionsList属性时,它无法找到该属性,因为您位于BackgroundWorker线程之外。在BackgroundWorker线程中完成工作后,RunWorkerCompleted将在原始线程中执行代码。

我们通常使用 BackgroundWorker.ReportProgress 方法从BGW线程到主线程进行通信。为了反过来传达(这似乎是你想要做的事情),我会考虑从BGW线程订阅主线程中的事件,以便BGW线程可以基于某些东西更新相关属性你是在主线程中做的。

Alternatively, check out this post

答案 4 :(得分:1)

.NET中的每个异常都将落在Application.Run(new frmMain());行上,因为此方法运行一个消息循环,除非窗口关闭,否则它将保持活动状态。

但是,你的异常是在GDI +上播放图像时总是抛出的常见异常,并且GDI已知内存泄漏导致此错误,最终由于没有更多内存可用错误。

一旦我看到你正在使用图像做什么,我就可以写更多关于你的错误的信息,很可能你的图像所用的记忆不会被释放而导致这个问题。在WPF中解决了这些带有图像的内存问题,在WPF上切换到图像操作不会导致这些错误。您仍然可以在.NET Forms中使用WPF来处理图像而不会导致内存错误,并根据需要使用Windows窗体。