Avoid race conditions when handling events