Search code examples
.netdisposeidisposable

How to dispose when application crashes


got a issue: I create singleton helper object that wraps PerformanceCounter objects. It implements IDisposable... But now I have spotted that when I close my test sample console host application, counters are still visible in perfmon tool (in production I will be hosted in Windows Service) , and are still running.

I figured out that Dispose is called inside finalizer, but then I don't dispose managed resources - which are PerformanceCounter objects. What should I do to make sure that resources are appropriately freed?

Thanks, Pawel


Solution

  • This is normal behavior for performance counters. They are global "objects" that exist even if no process is generating data for them. You can, for example, select one of the .NET perf counters even if not a single .NET program is running on the machine. If the counter is actively generating data even if you don't have a process running anymore that updates its value then you may have selected an inappropriate CounterType.

    Review the InstanceLifetime property to see if the Process value is appropriate for your counter.