簡體   English   中英

為什么我收到異常 System.Reflection.TargetInvocationException: 'Exception has been throwed by the target of an invocation.'?

[英]Why I'm getting exception System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'?

ExternalException: A generic error occurred in GDI+.


System.Reflection.TargetInvocationException
HResult=0x80131604
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
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.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
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.OnMessage(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(IntPtr 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 System.Windows.Forms.Application.Run(Form mainForm)
at Extract.Program.Main() in D:\Csharp Projects\Extract\Program.cs:line 19

This exception was originally thrown at this call stack:
System.Drawing.Image.Save(string, System.Drawing.Imaging.ImageCodecInfo, System.Drawing.Imaging.EncoderParameters)
System.Drawing.Image.Save(string, System.Drawing.Imaging.ImageFormat)
Extract.Form1.DownloadAsync() in Form1.cs
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Extract.Form1.DownloadImages() in Form1.cs
System.Runtime.CompilerServices.AsyncMethodBuilderCore.ThrowAsync.AnonymousMethod__6_0(object)

Inner Exception 1:
ExternalException: A generic error occurred in GDI+.

列表圖像和日期都包含 23 個項目。 異常不是超出索引,而是在最后一項 23 上拋出異常。它在所有圖像上繪制文本,但在項目 23 的循環結束時它拋出異常。

if (images.Length > 0)
{
for (int i = 0; i < images.Length; i++)
{
drawOnImage.DrawText(dates[i].ToString("ddd, dd MMM yyy HH':'mm"), images[i]);
}
}

也許是因為兩個列表包含相同數量的項目 23 ? 那我該怎么解決呢?

這是 DownloadAsync 方法的完整代碼,在底部我使用內存流和帶有 drawtext 的循環,並且異常僅在循環完成時發生在最后一個項目上。

private async Task DownloadAsync()
         {
             using (var client = new WebClient())
             {
                 client.DownloadFileCompleted += (s, e) =>
                 {
                     if (e.Error == null)
                     {
                         urlsCounter--;
    
                         var t = urls;
    
                         if (urlsCounter == 0)
                         {
                             CheckIfImagesExist();
    
                             btnRadarPath.Enabled = true;
                             btnSatellitePath.Enabled = true;
    
                             radCounter = 0;
                             satCounter = 0;
    
                             lblStatus.Text = "Completed.";
    
                             dates = rad.dates;
                             var images = System.IO.Directory.GetFiles(radarFolderImagesDownload,
                                   "*.gif", SearchOption.AllDirectories).OrderBy(x => x).ToArray();
    
                             Array.Sort(images, new MyComparer(false));
    
                             if (images.Length > 0)
                             {
                                 for (int i = 0; i < images.Length; i++)
                                 {
                                     drawOnImage.DrawText(dates[i].ToString("ddd, dd MMM yyy HH':'mm"), images[i]);
                                 }
                             }
    
                             GetImagesFiles();
                         }
                     }
                     else
                     {
                         string error = e.Error.ToString();
                     }
                 };
    
                 client.DownloadDataCompleted += (s, e) =>
                 {
                     if (e.Error == null)
                     {
                         urlsCounter--;
    
                         var t = urls;
    
                         if (urlsCounter == 0)
                         {
                             CheckIfImagesExist();
    
                             btnRadarPath.Enabled = true;
                             btnSatellitePath.Enabled = true;
    
                             radCounter = 0;
                             satCounter = 0;
    
                             lblStatus.Text = "Completed.";
    
                             dates = rad.dates;
                             var images = System.IO.Directory.GetFiles(radarFolderImagesDownload,
                                   "*.gif", SearchOption.AllDirectories).OrderBy(x => x).ToArray();
    
                             Array.Sort(images, new MyComparer(false));
    
                             if (images.Length > 0)
                             {
                                 for (int i = 0; i < images.Length; i++)
                                 {
                                     drawOnImage.DrawText(dates[i].ToString("ddd, dd MMM yyy HH':'mm"), images[i]);
                                 }
                             }
    
                             GetImagesFiles();
                         }
                     }
                 };
    
                 client.DownloadProgressChanged += (s, e) => tracker.SetProgress(e.BytesReceived, e.TotalBytesToReceive);
                 client.DownloadProgressChanged += (s, e) => lblAmount.Text = tracker.SizeSuffix(e.BytesReceived) + "/" + tracker.SizeSuffix(e.TotalBytesToReceive);
                 client.DownloadProgressChanged += (s, e) => lblSpeed.Text = tracker.GetBytesPerSecondString();
                 client.DownloadProgressChanged += (s, e) => myLong = Convert.ToInt64(client.ResponseHeaders["Content-Length"]);
                 client.DownloadProgressChanged += (s, e) =>
                 {
                     progressBar1.Value = e.ProgressPercentage;
                     label1.Text = e.ProgressPercentage + "%";
                 };
    
                 for (int i = 0; i < urls.Count; i++)
                 {
                     tracker.NewFile();
    
                     if (urls[i].Contains("Radar"))
                     {
                         await client.DownloadFileTaskAsync(new Uri(urls[i]), radarFolderImagesDownload + "\\image" + radCounter + ".gif");
    
                         radCounter++;
                     }
                     else
                     {
                         lblStatus.Text = "Downloading satellite";
    
                         using (MemoryStream ms = new MemoryStream(await client.DownloadDataTaskAsync(new Uri(urls[i]))))
                         {
                             Image img = Image.FromStream(ms, true);
                             img.Save(satelliteFolderImagesDownload + "\\image" + satCounter + ".gif", System.Drawing.Imaging.ImageFormat.Gif);
                         }
    
                         satCounter++;
                     }
                 }
             }
         }

猜測這是在與主線程不同的線程中發生的。 如果是這樣,您需要調用 UI 調用 (DrawText)。 為此,您可以將 Invoke 與委托一起使用。 為了更徹底,您可以檢查InvokeRequired以查看您是否確實需要調用該調用(即您在不同的線程上)。

Invoke(new Action(() =>
{
    drawOnImage.DrawText(dates[i].ToString("ddd, dd MMM yyy HH':'mm"), images[i]);
}));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM