@Evk already gave an answer, but it wasn't completely clear for me. After an extensive search through the documentation, I've compiled the following answer with reference to the documentation.
Long Answer:
When a Service stops, it's resources will be freed by the Garbage collector.
So what about the objects that implement IDisposable
? Will the unmanaged resources be freed? No. From Dispose Pattern:
The GC was specifically not designed to manage such unmanaged resources, which means that the responsibility for managing unmanaged resources lies in the hands of the developers.
So, what happens to the unmanaged resources? Are they never going to be freed?
There's still a chance
Object declares a virtual method Finalize (also called the finalizer) that is called by the GC before the object’s memory is reclaimed by the GC and can be overridden to release unmanaged resources.
This however has some drawbacks:
- The finalizer of an object is called after some undetermined period of time after the GC detects that it is eligible for collection.
- The finalizers are run between collections and so the object's memory is not released until the next round of garbage collection.
Although the documentation says that objects implementing IDisposable.Dispose
should either override the Finalize method or wrap the managed object in a SafeHandle so that if the consumer forgets to call Dispose
, the unmanaged resources are still freed; we could still end up in trouble.
From the Docs, the Finalize
method is called only if the derived type overrides it.
So, what if the developer has implemented neither of the 2 (Finalize
or SafeHandle
) above? Then we have a problem, there's no one to free the unmanged resources (at least the documentation doesn't say).
TLDR
The resources may or may not be freed (depending on circumstances explained above). So dispose all disposable objects (that are not disposed yet) in the Stop
method of your service.