A list of puns related to "Dispose pattern"
In our project we have a requirement of tracking execution time of some parts of code. In order to keep it DRY, we have implemented dispose pattern on "PerformanceTimer" class which logs the time on dispose. Code below.
public class PerformanceTimer : IDisposable
{
private readonly Stopwatch _stopwatch;
private readonly string _name;
public PerformanceTimer(string name)
{
_stopwatch = Stopwatch.StartNew();
_name = name;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposing)
return;
_stopwatch.Stop();
Logger.Information($"Execution time for {_name}: {_stopwatch.ElapsedMilliseconds} ms");
}
}
Usage:
using (new PerformanceTimer("foo"))
{
//code block
}
Now the issue is when the traffic is higher to the API, "Dispose" method is showing as hot spot in trace.
Is this a clean approach? How could we improve the performance?
Thanks in advance.
Everyone knows that IDisposable
is used for, and I've always used the simpler pattern of just implementing that one Dispose()
method. However later versions of Visual Studio have started to recommend (via warnings, no less) and provide scaffolding for a much more involved implementation of that pattern that requires a Dispose(bool disposing)
in addition to the Dispose()
.
Reading the documentation and the comments in the scaffolding, it makes sense when I would need to implement this more robust pattern: when I have unmannaged resources that absolutely must be freed at disposal or, failing that, at garbage collection.
Now, I've been working with .NET for 10 years now and I can count the number of times I've written a class that was responsible for managing a native resource on two hands and maybe a foot. Now, obviously, I've used files, streams, and various synchronization primitives, but always indirectly though framework or library classes who themselves are responsible for freeing those resources (when I call their Dispose
methods from within my simple Dispose
method).
But Visual Studio insists that I implement the full-blown dispose pattern every single time I implement IDisposable
. My question is: why? If I'm always using wrappers around resources and I just want to call their Dispose methods, it's the responsibility of those wrappers holding the unmanaged resources to do the actual cleanup. Why do I need to make my class overly complicated and ugly just to make VS stop warning me?
Edit: un-escaped all the backticks.
Fuck Vince
Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.