Issue 5165: Fix SearchContext occasionally closed prematurely 

PR for #5165