Sunday, January 21, 2007

I have a windows service program which depends a sql database. Sometimes, when the machine starts and my program tries to connect the database, the da

I have a windows service program which depends a sql database. Sometimes, when the machine starts and my program tries to connect the database, the database is not fully initialized yet, so it will throw an error in the startup procedure, and the service won't start.

I tried to a couple of solutions :

1> The first one I tried to is to set the recovery options of the service property, set it to restart the service if it fails. I actually misunderstand this property until I got an reply from a msdn newsgroup:

>
>> Recover options are only relevant if your service executable crashes, not
>> because of any HRESULTs which might lead to ending a process. If a
>> process is just ending by leaving all thread functions that is pretty OK
>> for the service control manager.
>>
>> You could try something like int *p = NULL; *p = 42; that should crash
>> your service and the restart should occur after the configured time
>> interval. Defaults to 1 minute IIRC.
2> Another solution I tried is to create a database watching thread. Instead of aborting from the startup procedure, the watching thread will keep checking the database connection, and notify the main thread when the database is available.

This approach is working, but it's a little bit overkilling. Everybody knows that the thread should really be avoided unless it's absolutely needed. In my case, if the database is not connected, my program is not workable any way, since I need the information from database to perform a lot of things...

The final solution I come out is putting the database checking in a while loop, which will check the database connection a configurable times (10 times by default) at start up in every 10 seconds.

This solution has 2 advantages:
1> The start up procedure of my service won't abort immediately if the database is not available. And in my cases, most of times, the database is available, it's just a little bit slow to come back.
2> If it really failed after trying to connect to the database after certain attempts, it may need some attention anyway.

No comments: