tags:

views:

138

answers:

1

I have a single instance WCF service class that is self hosted using a Windows service. I set up the service host in the OnStart event and I close the service in the OnStop event.

In the service class I implement a destructor and I have some clean-up code in there. Essentially the clean-up code serialises some internal objects to disk for next time and should produce two files.

What I am seeing is sometimes two files, sometimes one, sometimes empty files where there should be data in them. It seems like the destructor isn't getting time to complete the serialisation of the objects before the entire service process is ended.

Is this the typical way to do housekeeping just before a service shuts down, or is there a better way?

+3  A: 

The Destructor is a bad place to do this sort of logic b/c you can't be guaranteed what the state of any child or parent objects are. Some of them may have had their Dispose logic called by the time the destructor is called.

I would suggest you put an explicit Save method on your class, and call that during OnStop. There is no reason to hide the save in the Destructor, and hide the side effects from people reading your code.

Nick