Move duplicate code to functions.

Allows overriding the event processing loops in subclasses.

Suggested by Иван Ратников++