Fixed caching problems.

Cache writing didn't complete properly because the writer wasn't closed.