question

sharonglipman-9594 avatar image
0 Votes"
sharonglipman-9594 asked sharonglipman-9594 commented

Why I'm getting exception System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.' when trying to drawstring on images in a loop ?

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+.


Both Lists images and dates contain 23 items. The exception is not out of index but the exception throw on the last item 23.
It's drawing the text on all the images but in the end of the loop on item 23 it's throwing the exception.

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

Maybe because both Lists contain the same amount of items 23 ? how should I solve it then ?




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

dotnet-csharpwindows-forms
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@sharonglipman-9594, Based on your problem. the exception will only occur for the last item. Then, I suggest that you could check if the last file is corrupted. Also, I think Paul's thought is almost correct, I suggest that you could dispose the image object after you save the image to the file.

1 Vote 1 ·

I tried img.Dispose(); after the img.save line but it didn't help.

and I also tried again now using the old way with this single line to download

 await client.DownloadFileTaskAsync(new Uri(urls[i]), satelliteFolderImagesDownload + "\\image" + satCounter + ".gif");


and it's working fine

so the problem is still with the memorystream or something because it's working without a problem on the old/first way.

0 Votes 0 ·

1 Answer

Paul-5034 avatar image
1 Vote"
Paul-5034 answered sharonglipman-9594 commented

It looks like the exception is being thrown from inside your Form1.DownloadAsync method when you're calling Image.Save.

It's hard to diagnose further without seeing more of your Form1 class but whenever I've encountered the error "A generic error occurred in GDI+" it's often been because I have two open two images attempting to save to the same location & one's locked the file, then the second throws that exception because it can't gain exclusive write access to it.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I updated the question added the full DownloadAsync method

it's a bit strange because the exception happens in the loop only on the last item or after the last item when the loop finish and not on every item.

0 Votes 0 ·