Added a better thread handling.