Writes to the database in a separate thread.