Refactored session shutdown code to properly wait for thread termination.

Fixes issue #5543.