Use try-finally to ensure writes are always flushed