VB/C#:将一次性对象放置在全局范围内:这样可以吗?
作为一项优化,我决定将一个我经常需要的对象 - 带有整个关卡预渲染图像的 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 是全局范围)
问题:这从根本上来说合理吗?
它工作得很好,但我不禁觉得这种事情是不鼓励的......
As an optimization, I decided to put an object I frequently need - an SDL surface with a prerendered image of the entire level (called S_AreaBMP) - at global scope.
Now it doesn't have to be created and destroyed in the DrawScreen function every frame. I only need to dispose and change it when a new level or GFX sheet is loaded, which I do via this function:
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 and S_AreaBMP are global scope)
Question: Is this fundamentally sound?
It works fine, but I can't help but feel that this sort of thing is discouraged...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您基本上是在全局范围内创建静态变量。这样做在技术上没有任何错误,但通常更好的选择是使用 之类的东西来包装它单例模式。这将使控制对此的访问变得更容易,并且可能更容易以提供更好的线程安全性、此逻辑的封装等的方式包装资源。
You're basically making a static variable at a global scope. There isn't anything technically incorrect in doing this, but it's usually a better option to wrap this using something like the Singleton pattern. This would make it easier to control access to this, and potentially easier to wrap the resource in a way to provide better thread safety, encapsulation of this logic, etc.
线程安全将是我最关心的问题。特别是,如果在PrepareAreaImage()执行期间调用PrepareAreaImage,或者在PrepareAreaImage()执行期间访问S_AreaBMP,会发生什么情况。
Thread safety would be my biggest concern. Particularly, what happens if PrepareAreaImage is called when it is already executing, or S_AreaBMP is accessed sometime during PrepareAreaImage()'s execution.