Any insight why this should work? The OP claimed that their original code, when the problem happens, never gets to and past
echo "Foobar opened.". Why shall it get to your wait then? In other words: if your code doesn't hang, then even more the OP's code should not hang, because it should get to echo earlier, i.e. without waiting. What exactly does your wait do to avoid the hanging the OP allegedly experienced? Without explanation this answer is pure voodoo, I doubt it truly works. My hypothesis is in my comments under the question.