Use with block to avoid deadlock

If any of the IO actions fail at least the lock would be released.