WinForms specific analyzers
See original GitHub issueThere are some specific cases I’ve run into when analyzing IDisposable
usages in a large legacy WinForms app that has led me to identify some cases where specific analysis rules would make sense. Some of these I’m not 100% sure what the best course would be to address the specific issue, but I think it’s at least worth a discussion.
1. .Show()
vs .ShowDialog()
For example, when showing a form as a dialog, it ought to be properly disposed in the usual pattern, since it’s effectively deterministic in its life cycle (i.e. it blocks the current method and no other forms can typically be accessed until it is closed, after which it’s usually safe to dispose since it shouldn’t need to be used again).
However, there are many cases where you create a Form
and use Show()
rather than ShowDialog()
when the life cycle of the form is completely orthogonal and unknown to the calling code. In these cases it doesn’t make sense to explicitly dispose since we have no way of knowing when the form will actually be closed.
So a proposal there could be for a specific analysis of disposal for Form
and/or Control
instances where the Show()
method is called, rather than ShowDialog()
.
2. Variables added to the components
instance field
Another example I’ve run into is that in some cases there will be local variables initialized (i.e. a background worker) whose life cycle is unknown to the method that instantiates it, but that should not outlive the form, so it can be added to the designer-generated instance field components
which disposes all IDisposable
items it contains when the form is disposed.
In these cases it would make sense to check if the variable is added to either just the components
auto-generated field, or else some sort of instance field which is itself disposed eventually.
Issue Analytics
- State:
- Created 4 years ago
- Comments:12
Top GitHub Comments
I don’t think it’s problematic. When Form.Close is eventually called, it disposes.
So as I said, I can’t guarantee that my knowledge on this is 100% correct, but here are a few use cases.
components
field is disposed of.the lifetime of the
OtherForm
cannot be known by the calling method, it may outlive the calling method or class itself. So in this case it won’t make sense to explicitly dispose of at all.since the
ShowDialog()
method only returns after the form closes, it makes sense to ensure that the form is disposed of properly, so the existing analyzers fit just fine.