I am developing a .NET Windows service that is creating a couple of threads and then uses these threads to send print jobs to printers (there is a thread for each printer). I have some issues which sometimes can be fixed by restarting the service. Some issues also arise when the service has been running for a while. This makes me suspect a possible memory leak. So, a couple of questions:
Would a garbage collector collect an object if it was created inside a thread, or will the object exist until the thread is stopped/terminated?
What tools can I use to monitor the amount of memory used by a Windows service and by a thread that I am starting programmatically?
All objects are created inside threads. Every instruction ever executed is within a thread. Objects will be garbage collected at some point after there are no live references to them. Objects don’t “belong” to the thread they were created on.
For monitoring the service, you can use
perfmonwhich has plenty of counters for things like garbage collection. For more detailed analysis of where you may be leaking objects, you should use a profiler. All of this is likely to be made simpler if your program can also run as a non-service. (You may want to separate it out into a “launcher” part and then a library which can be used either from the service or from a console application.)