Fix rare crash at shutdown