Implementing transaction processing to persist application data
Let’s say an application needs to persist mostly immutable data. Let’s say the application’s data files can grow fairly large. How would you implement a simple transaction processing so that changes are either successfully committed or rolled back?
The only requirement i开发者_如何学Gos to use built-in .Net libraries. (no databases, no third party libraries)
Here’s my current solution. The data file will have three main sections: (1) header, (2) data, (3) index. For now, the header section simply contains an offset to the start of the index section. The data section will store mostly immutable data. The index section will contain serialized objects with enough information to access the data section.
When the application starts, it only needs to deserialize objects from index section. Anything from the data section can be fetched as needed. As the application gets ready to write changes, it makes a temporary copy of the original header and index sections. These would be small relative to the data section. New data would then be appended to the original data section. Once all data has been written, in memory objects would be serialized to the end of the file to become the new index section.
If all this goes without a hitch, the temporary file can be deleted. If something goes wrong, the temporary file can be used to restore the data file to its original state.
Will this work or is there a more elegant approach?
It would be much easier to use the transactional file system on Vista, Windows 7 or Windows 2008 It can be used from within .NET
How you implement such a thing greatly depends on the requirements: security, level of isolation, rollback and forward features, in fact you'll need to specify all ACID properties in detail to be able to make the design. That is not something to underestimate.
The databases that I know use a write ahead log way of solving some of the details.
To be able to help you better we need more specific details and perhaps more reasons why you are doing this so we can think along.
精彩评论