开发者

.Net - Dispose correctly children object

From code analysis (Visual studio), I got this warning:

Warning 2 CA2000 : Microsoft.Reliability : ... Call System.IDisposable.Dispose on object 'l' before all references to it are out of scope...

So, I changed the code :

开发者_运维知识库
Dim l As LiteralControl = New LiteralControl
AddHandler l.DataBinding, AddressOf OnDataBinding
container.Controls.Add(l)

to

Dim l As LiteralControl = Nothing
Try
    l = New LiteralControl
    AddHandler l.DataBinding, AddressOf OnDataBinding
    container.Controls.Add(l)
Finally
    If Not l Is Nothing Then
        l.Dispose()
    End If
End Try

The warning disappear but then the literal control isn't anymore being displayed on the page...

EDIT

Note that the code come from a Microsoft web page : http://msdn.microsoft.com/en-us/library/system.web.ui.itemplate.instantiatein.aspx


the warning is really about how the item could be created and then never actually hooked up to the container. hypothetically (but not realisticly), the AddHandler call could fail, and then the control would never be added to the container, and then nobody would ever dispose it.

instead of disposing on the finally (which is destroying your object all the time) you need to change that to a catch, and dispose in the catch, then rethrow the exception.

That will get rid of the warning and give you correct handling of dispose. Yes, in this specific case it isn't realistic, but it is possible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜