ajh's picture

OpenTK freeze in GameWindow main loop, and possible fix.

I've been using OpenTK for a hobby application recently and found my application "locking up" seemingly at random. By "locking up" I mean that my overridden OnRenderFrame and OnUpdateFrame methods were no longer being called by GameWindow. This would occur from just a couple of seconds after starting the application, up to minutes later.

My development environment is a VirtualBox virtual machine running WIndows XP Pro SP3, Visual Studio 2008 and .NET 2.0, 3.5 and 4.0. The host machine is an AMD processor, running WIndows Pro 7 64bit.

I struggled with this issue for a while but eventually realised I could look at the OpenTK source code and build my own debug version to step into the GameWindow code. Having done this I ran my application against the debug OpenTK and after a while actually found that the so called lock up was happening in GameWindow.RaiseUpdateFrame at the lines:

double time = update_watch.Elapsed.TotalSeconds;
if (time <= 0) return;

At this point I checked the value of the time variable and it showed something like -365 seconds (note the minus sign).

As I continued to run the code, this value slowly increased towards zero, but of course the method simply returns while it is 0 or less and does not call my overriden OnUpdateFrame, hence my application appears to lock up.

After doing some reasearch I found this forum post at Microsoft that describes closely the behaviour I was seeing:


As described on that page, a workaround is to simply ignore or treat negative elapsed times as zero. In my custom OpenTK build I replaced the above with:

            if (time <= 0)
                if (time >= -1.0) return;
                    time = 0;

(I notice the GameWindow.RaiseUpdateFrame method has very similar code so I have applied the change there as well.)

After this change I have been able to successfully run the application for hours on end, without the lockup.

It seems very unclear, the problem appears to be something to do with the Stopwatch implementation in the .NET Framework possibly in conjunction with AMD processors and/or virtual machines.

However the key point is that the .NET Stopwatch class can bizarrely produce negative elapsed times and if it does OpenTK will appear to lock up until the elapsed time is no longer negative.

Therefore I put forward the code change above as a possible fix to ensure OpenTK can handle this (bizarre) but frustrating bug.

I'm very interested in the opinions of developers of OpenTK regarding this possible change. (OpenTK is a great library BTW).



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Robmaister's picture

I would recommend submitting this as a bug report here: http://www.opentk.com/project/issues/opentk

Very interesting find, though.

ajh's picture

Thanks for the tip, I've added this issue over there.