"nickdu" <nickdu@discussions.microsoft.com> schrieb:
> Someone suggested that calling Control.CreateGraphics() is expensive and
> thus
> it might be a good idea to cache the returned Graphics object. Is this
> true?
No. 'Graphics' objects should not be cached because they will get invalid
if the underlying window handle gets recreated.

Signature
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>
nickdu - 08 Feb 2006 13:19 GMT
So they shouldn't be cached just because of recreating the window, or as I
mention below, does it hold onto a scarce resource (DC?)? I think someone
indicated a third party control library which caches the Graphics object and
re-caches (lets go of the current one and caches a new one) it each time the
window is resized. Someone else pointed me to:
http://msdn.microsoft.com/chats/transcripts/vstudio/vstudio_062602.aspx
which contains:
PeterG_MS
Q: Regarding overhead of passing objects to event handlers (such as
Graphics). There's more overhead than passing a pointer. The object must be
created and initialized. For every event, that seems like it would be a lot
of overhead. No?
PeterG_MS
A: Creating a Graphics object would have some significant overhead -- I
don't really know how much. But just passing a Graphics object has little
cost. So one way to improve performance would be a cache a Graphics object
and pass the same way on each event invocation, if possible.
I would rather stay away from caching the graphics object if possible.
Again my assumption is that if it's expensive to create the graphics object
and there is no harm in caching it the underlying framework (Windows / .NET)
would have cached it for us.

Signature
Thanks,
Nick
> "nickdu" <nickdu@discussions.microsoft.com> schrieb:
> > Someone suggested that calling Control.CreateGraphics() is expensive and
[quoted text clipped - 4 lines]
> No. 'Graphics' objects should not be cached because they will get invalid
> if the underlying window handle gets recreated.
Hi Nickdu:
All graphics objects are created based on current graphics context of the
control so please drop the ideas of caching them.
> Someone suggested that calling Control.CreateGraphics() is expensive and thus
> it might be a good idea to cache the returned Graphics object. Is this true?
[quoted text clipped - 10 lines]
>
> (Also posted on the .NET drawing newsgroup)