NPersist Feature Guide: Multi level object caching

An instance of the NPersist context object can be used as the data source for one or multiple other “child” context instances, which can in turn be data sources for even further child contexts and so on.

Objects are cached per context, meaning that if you ask for the Employee with ID = 42 from a certain context and then from one of its child contexts, two different instances will be returned. That means that changing an object from a child context will not affect the object with the same type and identity in its parent context.

Committing the changes in a child context will cause all changes to the objects in that context to be committed to the objects in the parent context. The parent context can then be committed to forward the changes to the objects in its parent context and so on until the root context is reached which might perform the changes to a relational database, an xml document or send them to an application server with a Web Service call.

A use case for this feature could be a WinForms application where opening a new form (particularly if it is not modal) would mean that the form would get its own child context, mapping to the parent context in the parent form.

If the user goes on to click the OK button in the new form, the changes to the child context is committed to the parent context in the parent form, but if the user clicks Cancel, the child context can simply be thrown away and none of the changes the user performed in the form will affect the objects in the parent context.

This use case is a good illustration of how the ability to “nest” contexts in this way provides an interesting way to deal with shared state in multithreaded applications. Each thread gets its own child context mapping to the root context in the main thread. Each thread thus gets a local copy of the shared state that it can update in isolation and then discard or commit the changes back to the shared copy.

The approach even supports using optimistic concurrency to allow threads to update the main copy in a safe way without writing over the unseen changes of another thread.

Last edited Feb 23, 2008 at 4:10 AM by matshelander, version 1

Comments

No comments yet.