简体   繁体   English

NHibernate +线程

[英]NHibernate + threads

I have nearly such code: 我几乎有这样的代码:

public class WCFService
{
    public OperationResult Create(...)
    {
        List<SomeClass> classList = new List<SomeClass>();//Items are got from db using       NHibernate
        ...
        Thread t = new Thread(delegate () { 
            foreach ( item in classList)
            {
                Method(item);
            }
        }
    ...
    return new OperationResult();
    }

    public void Method ( List<SomeClass> list) //doesn't use NHibernate Session
    {
    Conslole.Writeline(list.ToString());
    }

}

void main()
{
    WCFService service = new WCFService();
    service.Create(...);
}

After execution in console output there are only part of List. 在控制台输出中执行后,只有List的一部分。 I think Method can't get access to elements of list. 我认为Method无法访问列表元素。 When debugging there is such message instead of variable value : "Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation". 调试时,将显示以下消息,而不是变量值:“由于先前的功能评估超时,功能评估被禁用。您必须继续执行才能重新启用功能评估”。 Or LazyInitialization Exception "Could not initialize proxy - no Session". 或LazyInitialization异常“无法初始化代理-没有会话”。 Is problem in NHibernate session or something else? NHibernate会话中是否有问题? And how can I solve it? 我该如何解决呢? Method is in separate thread because it takes too much time, and result of creation need to be returned as fast as possible. 方法在单独的线程中,因为它花费了太多时间,并且创建结果需要尽快返回。

You get the LazyInitialization exception because the method is trying to access a property which is not initialized. 您会收到LazyInitialization异常,因为该方法试图访问未初始化的属性。 By default NH associations are lazy loaded, so upon access to the property, NH tries to load the data from the session, which of course by that time is long gone and disposed of. 默认情况下,NH关联是延迟加载的,因此在访问该属性时,NH会尝试从会话中加载数据,这当然已经很久了并且已被废弃。

A few options: 一些选择:

  1. Eager load the associations in your mapping with 'lazy=false' 渴望使用“ lazy = false”在映射中加载关联
  2. Eager load the associations in your query with 'FetchMode=join' 渴望使用“ FetchMode = join”在查询中加载关联
  3. Manually do the loading. 手动执行加载。 After you get your entities, access the properties to ensure they are loaded (or use NHibernateUtil.Initialize() on the associations). 获取实体后,访问属性以确保已加载它们(或在关联上使用NHibernateUtil.Initialize())。
  4. Do something like this http://trentacular.com/2009/08/how-to-use-nhibernate-lazy-initializing-proxies-with-web-services-or-wcf/ 做这样的事情http://trentacular.com/2009/08/how-to-use-nhibernate-lazy-initializing-proxies-with-web-services-or-wcf/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM