[RESOLVED] XNA ViewPort - Device reset fails on resize
As an introduction to XNA, I'm trying out the ViewPort code Jenner kindly posted in this thread (post #11) on the VB.Net forum.
When I resize the viewport (e.g. by resizing the parent form on which the viewport is anchored to 3 sides) the device reset fails with an "Unknown Error". It doesn't necessarily happen the first time the Resized event fires but generally within three times. I can't see anything in the stack trace that explains the problem; everything looks as expected up to the reset. The reset code, which is called from the control's Resize or SizeChanged event, is as follows:
Code:
Private Sub ResetGraphicsDevice()
If gDevice Is Nothing OrElse Me.Width = 0 OrElse Me.Height = 0 Then Return
gDevice.PresentationParameters.BackBufferWidth = Me.Width
gDevice.PresentationParameters.BackBufferHeight = Me.Height
Try
gDevice.Reset()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
Any ideas?
BB
Re: XNA ViewPort - Device reset fails on resize
Ahh... I see the issue. When the graphics Device is resetting due to the resize-event, you need to suspend drawing to it. This is super easy because I'm already using a Monitor to control draw execution. You can use the same Monitor to reset the device and halt drawing.
Change the "ResetGraphicsDevice" sub to the following:
Code:
Private Sub ResetGraphicsDevice()
If gDevice Is Nothing OrElse Me.Width = 0 OrElse Me.Height = 0 Then Return
If Threading.Monitor.TryEnter(monitorObject) Then
Try
gDevice.PresentationParameters.BackBufferWidth = Me.Width
gDevice.PresentationParameters.BackBufferHeight = Me.Height
gDevice.Reset()
Finally
Threading.Monitor.Exit(monitorObject)
End Try
End If
End Sub
Now, when it's drawing, it won't call reset. When it's resetting, it won't call drawing. Whichever routine has the monitorObject locked down is the one with exclusive control over it. Basically, if it's in the middle of a draw, and you try to resize it, thus reset it, it will not happen until the program is out of the draw loop. When it does get a chance to reset itself, the draw routine is skipped until it's done.
Re: XNA ViewPort - Device reset fails on resize
That does the trick:). It's also a nice illustration of the use of a Monitor which may prove useful in other situations. I can't rate you because I already did so recently, but many thanks and plaudits:thumb::thumb::thumb:.
I think I am going to have a clutch of other questions to ask about this XNA example, but I'll save them for another thread. BB
Re: [RESOLVED] XNA ViewPort - Device reset fails on resize
Thanks much! You know where to find me. :)