Refactor threading code to use Tasks again (regression tested for thread safety).