Reputation: 834
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (processFileBackgroundWorker != null)
{
processFileBackgroundWorker.Dispose();
processFileBackgroundWorker = null;
}
}
}
I am using a background worker in my view model, and I get the CA1001 error in fxcop. I understand that I need to inherit from Idisposable, and implement the above interface. I am more just curious as to how this works and if simply adding in this code arbitrarily in my class will accomplish anything. I tried setting a break point and this code is never called or utilized, and I would appreciate any guidance in how to properly implement it.
Upvotes: 1
Views: 691
Reputation: 37059
If fxcop pounds its spoon on the tray and demands IDisposable
, and it's not an option to get rid of fxcop, I guess you're stuck paying your taxes.
It's a bit silly in this particular case, because IDisposable
is for disposing unmanaged resources when an object goes out of the scope of a using
block or a try
/catch
, and viewmodels don't go out of scope in that way. So in normal viewmodel usage, nothing calls Dispose()
.
But you do often discard them before program exit (at program exit, nobody cares if anything gets disposed -- it's all going straight in the dumpster). I would implement IDisposable
, make it correctly dispose of the BackgroundWorker
as you're doing, and if there is a point in your code where an instance of that viewmodel is discarded, I would explicitly call Dispose()
on it. You don't need IDisposable
for that, but it's harmless.
Upvotes: 1