Nhibernate 中的多线程工作单元
我们正在使用 NHibernate 开发 ac# windows 服务,该服务应该处理一批记录。
该服务必须处理大约 6000 条记录,目前处理这些记录需要大约 3 个小时。会产生大量数据库命中,在我们努力最大程度地减少这些命中的同时,我们也在探索多线程选项以提高性能。
我们使用 UnitOfWork 模式来访问 NHibernate 会话。
该服务大致如下:
public class BatchService
{
public DoWork()
{
StartUnitOfWork();
foreach ( var record in recordsToBeProcessed)
{
Process(record);
// Perform lots of db operations
}
StopUnitOfWork();
}
}
我们正在考虑使用任务并行库来尝试批量处理这些记录(使用 Parallel.Foreach () 方法)。 根据我到目前为止所读到的有关 NHibernate 的内容,我们应该为每个线程提供一个单独的 NHibernate 会话。
我的问题是我们如何提供这个..考虑到只允许一个会话可用的 UnitOfWork 模式。
我应该考虑将 UnitOfWork 围绕单个记录的处理吗?
非常感谢任何帮助。
谢谢
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 multithreading 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好的方法是为每个线程启动一个新的工作单元,使用线程静态上下文会话
NHibernate.Context.ThreadStaticSessionContext
。您必须了解分离的实体。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.最简单的方法是将记录的每个处理包装在它自己的工作单元中,然后在它自己的线程上运行每个 UOW。您需要确保每个 UOW 和会话在单个线程上启动、使用和完成。
为了获得性能,您可以将这批记录拆分为较小的批次,然后将这些较小批次的处理包装到 UOW 中并在单独的线程上执行它们。
根据您的工作负载,使用二级缓存 (memcached/membase) 可能会显着提高您的性能。 (例如,如果您需要为每个处理从数据库读取一些记录)
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 )