Improved attachment checking to prevent repeadetly calling detach.