Some fixes to the window code to prevent use-after-free and concurrent access.
Improves the situation in #533