Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
HI,
I'm working on my game loop and when disposing the graphics device form
I get 'ObjectDisposedException'. I put the code that draws the back buffer to
the target surface in 'try... end try' statements like this:
VB
Try
   _bbg = Me.CreateGraphics
   _bbg.DrawImageUnscaled(_bb, 0, 0)
Catch ex As ObjectDisposedException
End Try

and this solved the problem, but then I remember that I read somewhere
that 'try' statements are heavy and I've decided to replace them
with a simple boolean expression that checks whether the form is about to
be disposed or not:
VB
If booKill = False Then
   _bbg = Me.CreateGraphics
   _bbg.DrawImageUnscaled(_bb, 0, 0)
End If

That also do the trick without throwing exceptions, but now I'm wondering
which one of the both examples is faster?
Posted
Updated 22-Apr-13 0:50am
v2

I would say both because booKill is boolean and doesn't really guarantee anything about _bb. Unless you cannot do anything to fix it, because then a try..catch is most of the time just useless.

If booKill = False Then
  Try
   _bbg = Me.CreateGraphics
   _bbg.DrawImageUnscaled(_bb, 0, 0)
  Catch ...
    Fix code...
  End Try
End If


Good luck!
 
Share this answer
 
You're confusing defensive programming (If booKill = False) with exception handling (Try ... Catch) ... Me.CreateGraphics might still throw an exception but with just the boolean check you wouldn't capture it.

But to answer your question about "fastest" ... try writing a small test program to process large volumes using both methods ... In simplistic terms, the boolean check is always executed whereas the Try-Catch processing only gets invoked if there's an exception, which implies that the latter would be "faster". I doubt you'll really notice the difference.

In terms of making it clear what's going on, writing defensively and handling exceptions properly then I would suggest something close to E.F. Nijboer's solution
 
Share this answer
 
Comments
O.G.I. 22-Apr-13 7:53am    
Thank you for the quick response guys, about the exception, I think I found good solution in the forum:
How to close a multi-threaded .NET Windows Forms application and prevent the ObjectDisposedException from getting thrown[^]

I didn't know that the 'try' statements will be invoked only if exception occurs, I thought that it is some kind of check that repeats each time the code inside is executed, thank you CHill60.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900