From this thread, Dispose()
must be explicitly called for disposable objects.
What happens when a Windows Service stops? Are the resources used by these objects automatically freed? Or should they be disposed before the service stops like this:
public void Stop()
{
cancellationTokenSource.Cancel();
waitForAllTasksToExit();
cancellationTokenSource.Dispose();
}
"It's a good practice to dispose", "They should be freed when the service stops" is what I think too. But is there a concrete answer with reference to the documentation?
It depends on what are "resources used by these objects". Dispose
method itself won't be called on process exit, but most objects that contain "unmanaged" resources in addition to Dispose
also have finalizer. Finalizer will be called on process exit, but it might not be called on process crash. Now, on process exit (or crash) the following happens:
Any resources allocated by the process are freed.
All kernel objects are closed.
Kernel objects are for example file handles, sockets and so on. So even if process crashed and finalizers are not run (or there was no finalizer at all) - things like files or database\network connections will still be closed by OS.
You might have broader definition of unmanaged resource. Unmanaged means not managed by .NET Framework garbage collector. If I for example create a file on disk when creating some object and going to delete this file when this object is disposed - you might say this is also "unmanaged" resource. Such resource is not known to OS and it will not be "cleaned" if I've not implemented finalizer or finalizer was not called because of process crash.
All in all - if object implements IDisposable
- dispose it even before process exit. You might not know the intentions of that object developer, whether it has a finalizer or not - so it's better to always explicitly dispose it even before process exit.