Fixes bug 929197 - Make sure connection closing can happen before doing it.
Merge pull request #1610 from AdrianGaudebert/929197-refactor-connection

Fixes bug 929197 - Make sure connection closing can happen before doing it.