AccessViolationException in Windows Services

time to read 8 min | 1522 words

I wrote a Windows Service and I couldn't get the service to start properly. After trying too long to debug it in a service mode, I gave up and tried running it as a console application, I immediately got the following error:

Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

I so thought that I left those kind of bugs when I left C++. Just to be clear, there isn't a hint of unsafe / unmanaged code in the application. It turned out that my initialization was throwing an exception, and because my error handling was calling Stop(). This seems to be the trigger.

I repreduce the error with this code:

class Program

{

    static void Main (string[] args)

    {

        new TestSrv().SimulateStart();

    }

 

    public class TestSrv : ServiceBase

    {

 

        public void SimulateStart()

        {

            this.OnStart(null);

        }

 

        protected override void OnStart(string[] args)

        {

            try

            {

                throw new Exception();

            }

            catch (Exception e)

            {

                //log exception

                this.Stop();

            }

        }

    }

}

The fix was not to call Stop() from OnStart(), but to use Environment.Exit(-1), which tells the Services Manager that we exited with errors.

I filed a ladybug here.