VB / C#:将可处置对象放在全局范围内:这样可以吗?

时间:2009-09-03 19:42:10

标签: .net resources bitmap dispose

作为一种优化,我决定在全球范围内放置一个我经常需要的对象 - 一个SDL表面,其中包含整个级别的预渲染图像(称为S_AreaBMP)。 现在不必每次都在DrawScreen函数中创建和销毁它。我只需要在加载新级别或GFX表时进行处理和更改,我通过此功能执行此操作:

Public Sub PrepareAreaImage()

    ''#dispose old image before it becomes unreferenced
    If AreaBMPExists
        S_AreaBMP.Dispose()
    End If
    AreaBMPExists = True

    ''#declare an appropriately sized bitmap w/ a GDI Graphics object
    Dim AreaBMP As Bitmap = New Bitmap(Area.W * TLDIM, Area.H * TLDIM)
    Dim AreaGrph As Graphics = Graphics.FromImage(AreaBMP)

    ''#...(omitted: iterate through Area and draw each tile to AreaBMP)

    ''#Store to the SDL surface
    S_AreaBMP = New SdlDotNet.Graphics.Surface(AreaBMP)

    ''#Dispose
    AreaBMP.Dispose()
    AreaGrph.Dispose()
End Sub

(AreaBMPExists和S_AreaBMP是全局范围)

问题:这基本上是否合理?

它工作正常,但我不禁觉得这种事情是灰心丧气的......

2 个答案:

答案 0 :(得分:1)

您基本上是在全局范围内创建静态变量。这样做在技术上没有任何不正确之处,但通常使用类似Singleton pattern之类的东西来包装它是更好的选择。这样可以更容易地控制对此的访问,并且可能更容易包装资源,以提供更好的线程安全性,封装此逻辑等。

答案 1 :(得分:0)

线程安全将是我最关心的问题。特别是,如果PrepareAreaImage在执行时被调用会发生什么,或者在PrepareAreaImage()执行期间的某个时间访问S_AreaBMP。