开发者

Multithread UnitOfWork in Nhibernate

We are working on a c# windows service using NHibernate which is supposed to process a batch of records.

The service has to process about 6000 odd records and its taking about 3 hours at present to process these. There are a lot of db hits incurred and while we are trying to minimize these , we are also exploring multit开发者_高级运维hreading options to improve performance.

We are using the UnitOfWork pattern to access the NHibernate session.

This is roughly how the service looks :

public class BatchService
    {
        public DoWork()
        {
           StartUnitOfWork();

           foreach ( var record in recordsToBeProcessed)
           {
              Process(record);
              // Perform lots of db operations
           }

           StopUnitOfWork();
        }
    }

We were thinking of using the Task Parallel Library to try to process these records in batches ( using the Parallel.Foreach () method). From what I have read about NHibernate so far , we should provide each thread a separate NHibernate session.

My query is how do we supply this ..considering the UnitOfWork pattern which only allows one session to be available.

Should I be looking at wrapping a UnitOfWork around the processing of a single record ?

Any help much appreciated.

Thanks


The best way is to start a new unitofwork for each thread, use a thread-static contextual session NHibernate.Context.ThreadStaticSessionContext. You must be aware of dettached entities.


The easiest way is to wrap each processing of a record in it's own unit of work and then run each UOW on it's own thread. You need to make sure that each UOW & session is started, used and completed on a single thread.

To gain performance you could split the batch of records in smaller batches and then wrap the processing of this smaller batches into UOWs and execute them on separate threads.

Depending on your workload using a second level cache (memcached/membase) might dramatically improve your performance. (eg if you need to read some records from the db for each processing )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜