views:

203

answers:

2

Hi *,

I've got a problem with an multi-threaded desktop application using Castle ActiveRecord in C#:

To keep the GUI alive while searching for the objects based on userinput I'm using the BackgroundWorker for the search-function. Some of the properties of the objects, especially some HasMany-Relations, are marked as Lazy.

Now, when the search is finished and the user selects an resulting object, some of the properties of this object should be displayed. But as the search was done by the BackgroundWorker in a different thread, accessing the properties fails as the session for the lazy-access is no longer available.

What will be the best way to do the search in an extra thread to keep the GUI alive and to access all properties correctly including those marked as lazy?

Thanks for any advise!

Regards sc911

A: 

A couple of options:

  • When querying, do an eager load of whatever you will need later in the main thread, thus avoiding lazy loading.
  • Use ISession.Lock() to reattach the entities to the ISession in the main thread.
Mauricio Scheffer
eager-loading: kind of a problem here, because the search results in multi objects from which the user selects only one. and only the properties of this selected is required. but search and selection are in different threads...ISession.Lock(): did not get this to work, sorry! any examples how to use it?
sc911
@sc911: re lock(), see http://intellect.dk/post/Detached-objects-in-nHibernate-and-Lazy-loading.aspx
Mauricio Scheffer
A: 

Solved it with this nice blog post here: http://www.darkside.co.za/archive/2008/09/09/castle-activerecord-lazy-loading-session-scopes-again.aspx

sc911
ActiveRecord already includes a per-thread SessionScope storage: http://github.com/castleproject/Castle.ActiveRecord/blob/master/src/Castle.ActiveRecord/Framework/Scopes/ThreadScopeInfo.cs
Mauricio Scheffer
which, as stated in the blog-post, is not working out for this special problem. I tried to use it, but then I do get the nice, old `failed to lazily initialize a collection of role: [...], no session or session was closed` error again.
sc911
If I understand correctly the code on that blog post is sharing sessions across threads, is that right? NHibernate sessions are not thread-safe, I recommend sticking to the per-thread strategy included in ActiveRecord.
Mauricio Scheffer
Try re-attaching the entities you got from the background thread to the foreground thread's session by using session.lock()
Mauricio Scheffer