正在重用GDI+反对不好的做法? (或者:如何使用许多嵌套的 using 块而不感到头疼?)
我目前正在为用户控件编写一个相当复杂的绘制方法,涉及大量的绘制代码。我知道所有 GDI+ 资源都需要正确处置,因此我将每个资源包装在 using
块中。
但是当我注意到我为三个不同的 SolidBrushes
使用了三个 using
块时,我想知道我是否不能重复使用它们。创建一个 SolidBrush
,用它绘图,分配不同的颜色,绘制其他内容等。然后在末尾放置一个 Dispose()
。
这样的事情是可取的还是我在这里想太多了?我也不太喜欢太多相互嵌套的 using
块。虽然这是一个很好的模式,但有时会妨碍可读性。
I'm currently writing a fairly complex paint method for a user control, involving a fair amount of drawing code. I know that all GDI+ resources need to be properly disposed so I wrap each of those in a using
block.
But when I noticed that I used three using
blocks for three different SolidBrushes
I wondered whether I couldn't just re-use them. Create a SolidBrush
, draw with it, assign a different color, draw something else, etc. And put a Dispose()
at the end.
Is such a thing advisable or am I thinking too hard here? I don't particularly like too many using
blocks nested in each other as well. While a nice pattern it hinders readability at times.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,重用是一种优化,而且可能还为时过早,因此:是的,这是一种不好的做法。我会等待明显的性能问题出现,然后寻找瓶颈。您将用一些(未知的)性能增益来换取管理这些组件状态的快速增加的复杂性。
顺便说一句,一种几乎被接受的嵌套使用块的形式如下所示:
Well, re-using is an optimization and it is probably premature and therefore: Yes it is a bad practice. I would wait for a clear performance problem to surface and then look for the bottleneck. You would be trading some (unknown) performance gains for the rapidly increasing complexity of managing the state of those components.
On a side note, one pretty much accepted form of nesting using-blocks looks like this:
我认为这种做法并没有什么不好。但我认为你可以重复使用创建的画笔。在我自己的用户控件中,如果我使用画笔,我会将它们存储在用户控件的本地变量中,并在处理用户控件时处理它们。
I think there is nothing bad with this practice. But i think you can reuse the created Brushes. In my own UserControls, if i use Brushes i store them in a local variable of the UserControl and dispose them of when i dispose the UserControl.
重用 GDI 对象本身并没有什么坏处。糟糕的是,同时存在的 GDI 对象数量超过了
您的显卡GDI 的处理能力。我早些时候由于缓存虚线笔和一些内容而遇到了问题刷子。我同事的代码(在同一个 WM_PAINT 中运行)完全没有问题,即使它没有缓存任何对象!只是我太聪明才导致 GDI 阻塞并抛出 OutOfMemoryException(它们可能意味着显卡内存不足)。
Re-using GDI objects is not bad in itself. What is bad is when there are too many GDI objects in existence at one time than
your graphics cardGDI can handle.I had earlier faced a problem as a result of caching a dashed pen and some brushes. My colleague's code (running within the same WM_PAINT) had no problems at all even though it did not cache any objects! Only my oversmartness was causing GDI to choke up and throw an OutOfMemoryException (they probably mean out of memory on the graphics card).