Fix Flush() race condition.

This fixes a potential race condition where the buffer is flushed more than needed.