More robust event and close handling

There were still some circumstances where we could get stuck reading
data and not respect close events properly. Move that logic to a more
central place in order to make it more reliable.
1 file changed