简体   繁体   English

TargetInvocationException未处理 - c#

[英]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 代码在frm5中运行

then the error shows at 然后错误显示在
Program.cs: 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()); 它在Application.Run(new frmMain());

it says TargetInvocationException was unhandled - Exception has been thrown by the target of an invocation. 它说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. 您正在执行frmMain构造函数中的一些代码,这些代码不应该在那里执行。 Move that code and execute it on Form Shown event. 移动该代码并在Form Shown事件上执行它。

It looks as though you're using a BackgroundWorker to do some work on a background thread. 看起来好像你正在使用BackgroundWorker在后台线程上做一些工作。 Check that you're not doing anything that must be done on the UI thread. 检查您是否在UI线程上没有做任何必须完成的事情。 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. 请注意,在各种情况下,COM方法抛出ArgumentException 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 . 如果参数为SafeNativeMethods.Gdip.StatusException或20,则SafeNativeMethods.Gdip.StatusException的源可能会抛出ArgumentException此处此处还有一些其他类似问题的帖子。

I'm not much of graphics man, but the failing line: 我不是图形人,但失败的线:

System.Drawing.Image.get_FrameDimensionsList() 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? 进行一些GDI +调用并且似乎想要图像的FrameDimensionsCount的某些值...它是你正在处理的GIF动画吗? Or TIFFs? 还是TIFF?

Check out the docs for GdipImageGetFrameDimensionsCount and see if anything twigs. 查看GdipImageGetFrameDimensionsCount的文档,看看是否有任何树枝。 Decompiled failing getter below: 下面的反编译失败的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;
        }
      }
    }

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. 当您尝试从frmStitch.backgroundWorker1_RunWorkerCompleted方法中获取FrameDimensionsList属性时,它无法找到该属性,因为您在BackgroundWorker线程之外。 RunWorkerCompleted executes code back in the original thread after you have finished your work in the BackgroundWorker thread. 在BackgroundWorker线程中完成工作后,RunWorkerCompleted将在原始线程中执行代码。

We normally use the BackgroundWorker.ReportProgress method to communicate from the BGW thread to the main thread. 我们通常使用BackgroundWorker.ReportProgress方法从BGW线程到主线程进行通信。 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. 为了反过来传达(这似乎是你想要做的事情),我会考虑从BGW线程订阅主线程中的事件,以便BGW线程可以基于某些东西更新相关属性你是在主线程中做的。

Alternatively, check out this post 或者,看看这篇文章

Every Exception in .NET will fall on the line Application.Run(new frmMain()); .NET中的每个异常都将落在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. 但是,您的异常是在GDI +上播放图像时总是抛出的常见异常,并且GDI已知内存泄漏导致此错误,最终由于没有更多内存可用错误。

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. 在WPF中解决了这些带有图像的内存问题,在WPF上切换到图像操作不会导致这些错误。 You can still use WPF inside .NET Forms to process images without causing memory errors and use Windows Forms as you need. 您仍然可以在.NET Forms中使用WPF来处理图像而不会导致内存错误,并根据需要使用Windows窗体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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