Made some cleanup steps more explicit.
Fixed a potential race condition where the close listener could be attached after the write had already completed.