8 Replies - 4355 Views - Last Post: 12 February 2016 - 02:54 PM Rate Topic: -----

#1 DroidDr   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 4
  • Joined: 11-February 16

C# app crash despite code in try/catch

Posted 11 February 2016 - 03:29 PM

Hi all,

I have a multithreaded forms application in C# 4.0. It is built like a service though, the gui is just looking at thing the threads are doing. The app crashed with the following event log in windows

Application: ChargerCameraCoordApp.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
Stack:
   at System.Drawing.SafeNativeMethods+Gdip.GdipSaveImageToFile(System.Runtime.InteropServices.HandleRef, System.String, System.Guid ByRef, System.Runtime.InteropServices.HandleRef)
   at System.Drawing.Image.Save(System.String, System.Drawing.Imaging.ImageCodecInfo, System.Drawing.Imaging.EncoderParameters)
   at ChargerCameraCoordApp.service_core.savePictureToDisk(System.Drawing.Bitmap, System.String, System.Drawing.Imaging.ImageFormat)
   at ChargerCameraCoordApp.service_core.PLCReadCommFunction(System.Object)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ThreadHelper.ThreadStart(System.Object)




My function ChargerCameraCoordApp.service_core.savePictureToDisk is a function that has a code to save a picture inside a try-catch block. I just do not get why it brought down the application?! Is it something peculiar to picture saving?


private static int savePictureToDisk(Bitmap myImage, String myFileName, ImageFormat myFormat )
        {
            int ret_val = 0;

            String moduleName = "savePictureToDisk";

            //if (myFormat != ImageFormat.Png && myFormat != ImageFormat.Bmp && myFormat != ImageFormat.Jpeg && myFormat != ImageFormat.Tiff) myFormat = ImageFormat.Png;

            try
            {
                //myImage.Save(myFileName, ImageFormat.Png);
                myImage.Save(myFileName, myFormat);
                ret_val = 1;
            }
            catch (Exception ex)
            {
                utilCl.I.appLog("Error saving image ->" + myFileName + "<- " + ex.Message, moduleName);
                ret_val = -1;
            }
            return ret_val;
        }





My application has threads that acquire pictures and are kept in memory until possibly one of 2 other threads will pick them up. I suspect a concurrent access on one of the pictures could be the cause, so I put lock blocks I forgot in the 2 threads when accessing the images. This may solve my issue, but I still do not get why my app crashed regardless if the code is in a try/catch block?!?!

Best wishes to all!

Is This A Good Question/Topic? 0
  • +

Replies To: C# app crash despite code in try/catch

#2 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: C# app crash despite code in try/catch

Posted 11 February 2016 - 05:28 PM

Maybe the exception was thrown in the Catch block.

Quote

I have a multithreaded forms application in C# 4.0

Do you know that's WAY out of date? Nobody does forms these days; its all WPF. And C# is currently version 6.
Also Microsoft just announced that support for .NET 4.0 and 4.5.x will soon be end-off-life. Its all the 4.6.x family these days. Just FYI.
And their latest deal with Intel indicates that new computers won't even be able to run anything less than Windows 8.1

So it might be time to update your target environment(s).
Was This Post Helpful? 0
  • +
  • -

#3 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6335
  • View blog
  • Posts: 21,746
  • Joined: 05-May 12

Re: C# app crash despite code in try/catch

Posted 11 February 2016 - 05:38 PM

You mentioned something about locks. In the back of my mind, there was a fragment of a memory about the C# compiler not catching exceptions while within a lock so as to prevent deadlocks, but I don't have time to try to do the needed Google searches to find the exact circumstances.
Was This Post Helpful? 1
  • +
  • -

#4 DroidDr   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 4
  • Joined: 11-February 16

Re: C# app crash despite code in try/catch

Posted 11 February 2016 - 08:24 PM

Thanks Skydiver, I will research this and figure it out.

Cheers!
Was This Post Helpful? 0
  • +
  • -

#5 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6335
  • View blog
  • Posts: 21,746
  • Joined: 05-May 12

Re: C# app crash despite code in try/catch

Posted 11 February 2016 - 11:02 PM

After digging around a bit, the deadlocking and throwing an exceptions seems to be specific to .NET 1.0 and .NET 1.1. What a waste of my fading memory capacity when that could have been used to store Monty Python skits instead.

Of course the answer was staring me in the face with your original post. "SafeNativeMethods" is just euphemism for a P/Invoke call into unmanaged code. If the unmanaged code throws an exception, the managed code will not know what to do with it. (I think there are some ways around this if it's an SEH exception, but I don't recall right now.)

Anyway, I managed to reproduce the problem by writing the following code:
ManagedConsole.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ManagedConsole
{
    class Program
    {
        [DllImport("UnmanagedDll.dll")]
        public static extern void CrashMe();

        static void Main(string[] args)
        {
            try
            {
                CrashMe();
            }

            catch (Exception e)
            {
                Console.Error.WriteLine("--- Managed Exception begins ---");
                Console.Error.WriteLine(e.ToString());
                Console.Error.WriteLine("--- Managed Exception ends ---");
            }
        }
    }
}



UnmanagedDll.cpp:
extern "C" __declspec(dllexport) void CrashMe()
{
    char * pch = nullptr;

    *pch = 0;
}



Windows event log entry:
Application: ManagedConsole.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
   at ManagedConsole.Program.CrashMe()
   at ManagedConsole.Program.Main(System.String[])



Program output:
D:\z\Test\TestUnmanagedException\ManagedConsole\bin\x64\Debug>dir
 Volume in drive D is FIZBAN-D
 Volume Serial Number is 223E-292A

 Directory of D:\z\Test\TestUnmanagedException\ManagedConsole\bin\x64\Debug

02/12/2016  00:48    <DIR>          .
02/12/2016  00:48    <DIR>          ..
02/12/2016  00:48             4,608 ManagedConsole.exe
02/12/2016  00:48            11,776 ManagedConsole.pdb
02/12/2016  00:41            22,688 ManagedConsole.vshost.exe
02/12/2016  00:48            56,320 UnmanagedDll.dll
02/12/2016  00:48               681 UnmanagedDll.exp
02/12/2016  00:48           278,756 UnmanagedDll.ilk
02/12/2016  00:48             1,836 UnmanagedDll.lib
02/12/2016  00:48           512,000 UnmanagedDll.pdb
               8 File(s)        888,665 bytes
               2 Dir(s)  438,703,063,040 bytes free

D:\z\Test\TestUnmanagedException\ManagedConsole\bin\x64\Debug>ManagedConsole.exe

Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
   at ManagedConsole.Program.CrashMe()
   at ManagedConsole.Program.Main(String[] args) in D:\z\Test\TestUnmanagedException\ManagedConsole\Program.cs:line 18



Was This Post Helpful? 3
  • +
  • -

#6 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6335
  • View blog
  • Posts: 21,746
  • Joined: 05-May 12

Re: C# app crash despite code in try/catch

Posted 12 February 2016 - 06:38 AM

As a quick aside, I originally targeted my "ManagedConsole" to build against .NET 4.0 just to limit the number of variables. Moving up to .NET 4.6.1 doesn't do anything different in terms of behavior. So although based on this StackOverflow answer it looks like the types of exceptions that cannot be caught have been evolving, this particular access violation seems to be consistent.

It was this MSDN article that gave me the impression that there maybe a way to catch SEH exceptions: CLR Inside Out - Handling Corrupted State Exceptions. If have time today, I'll try a few other things with "CrashMe.dll" to see what other mischief we can get into, including trying to do an INT 3 (aka Debugger break).
Was This Post Helpful? 1
  • +
  • -

#7 DroidDr   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 4
  • Joined: 11-February 16

Re: C# app crash despite code in try/catch

Posted 12 February 2016 - 06:56 AM

Skydiver,

Thanks, that makes sense. I did not know that unmanaged code based exceptions were not caught, and did not realize that the bitmap.Save method contains some. Thanks for opening my eyes to that.
I had a similar crash 1 month ago with my app, I was using System.Runtime.InteropServices.Marshal.Copy and also did not know why the exception was not caught there, I thought initially it was the program that ran out of mem, but that did not make sense either.

I will check how I can catch those exceptions or find another way to correct my problem.

You are very helpful, it is a great learning experience as I transition from C# novice to better :)
Was This Post Helpful? 0
  • +
  • -

#8 DroidDr   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 4
  • Joined: 11-February 16

Re: C# app crash despite code in try/catch

Posted 12 February 2016 - 02:23 PM

Hi,

I did a fair amount of reading on these exceptions today.

Here is another test to prove I catch Access violation exceptions.
Before I added HandleProcessCorruptedStateExceptions,
IntPtr ptr = new IntPtr(42);
System.Runtime.InteropServices.Marshal.StructureToPtr(42, ptr, true);

was crashing.

With this the access violation is caught.

using System.Runtime.ExceptionServices;
using System.Security;


        [HandleProcessCorruptedStateExceptions]
        [SecurityCritical]
        private void button2_Click(object sender, EventArgs e)
        {
            IntPtr ptr = new IntPtr(42);
            try
            {
                System.Runtime.InteropServices.Marshal.StructureToPtr(42, ptr, true);
            }
            catch (System.AccessViolationException sysEx)
            {
                MessageBox.Show("AccessViolationException " + sysEx.Message);
                MessageBox.Show("AccessViolationException source ->" + sysEx.Source);
                MessageBox.Show("AccessViolationException stack ->" + sysEx.StackTrace);
            }
            catch (System.StackOverflowException soverflEx)
            {
                MessageBox.Show("OverflowException " + soverflEx.Message);
                MessageBox.Show("OverflowException source ->" + soverflEx.Source);
                MessageBox.Show("OverflowException stack ->" + soverflEx.StackTrace);
            }
            catch (System.Runtime.InteropServices.SEHException sehEx)
            {
                MessageBox.Show("SEHException " + sehEx.Message);
                MessageBox.Show("SEHException hresult ->" + sehEx.ErrorCode);
                MessageBox.Show("SEHException source ->" + sehEx.Source);
                MessageBox.Show("SEHException stack ->" + sehEx.StackTrace);
            }
            catch(Exception ex)
            {
                MessageBox.Show("Exception ex" + ex.Message);
            }
        }



Now I have to check that if I do catch the exception in my app, it does not leave the rest of it in an uncertain state.

Thanks.
Was This Post Helpful? 1
  • +
  • -

#9 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6335
  • View blog
  • Posts: 21,746
  • Joined: 05-May 12

Re: C# app crash despite code in try/catch

Posted 12 February 2016 - 02:54 PM

Yay! That [HandleProcessCorruptedStateExceptions] does amazing things.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1