如何使这个线程安全

时间:2011-03-18 14:11:25

标签: fluent-nhibernate thread-safety sessionfactory

我有以下用于Fluent NHibernate的SessionFactory。

我收到错误

  

创建SessionFactory时使用了无效或不完整的配置。

具有

的InnerException
  

已添加具有相同键的项目。

这个问题偶尔会发生,我的应用程序大部分时间都能正常运行。

基于NHibernate: System.Argument Exception : An item with the same key has already been added我猜我的类不是线程安全的,这可以解释这个错误的间歇性。

using System;
using NHibernate;
using NHibernate.Cache;
using NHibernate.Cfg;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using WSS.Data.Domain;

namespace WSS.Data {
    public static class SessionFactory {
        private static ISessionFactory _factory = null;
        private static ISessionFactory GetFactory() {
            if (_factory == null) {
                NHibernate.Cfg.Configuration config;
                config = new NHibernate.Cfg.Configuration();
                config.Configure();
                if (config == null) {
                    throw new InvalidOperationException("NHibernate configuration is null.");
                }


                config.AddAssembly("WSS.Data");
                _factory = config.BuildSessionFactory();
                if (_factory == null) {
                    throw new InvalidOperationException("Call to Configuration.BuildSessionFactory() returned null.");
                }
            }
            return _factory;

        }

        private static ISessionFactory GetFluentFactory() {
            if(_factory == null) {
                _factory = Fluently.Configure()
                    .Database(MsSqlConfiguration.MsSql2000
                        .ConnectionString(c => c
                            .Is(ConnectionStrings.Auto))
                        .Cache(c => c
                            .UseQueryCache()
                            .ProviderClass())
                        .ShowSql())
                    .Mappings(m => m
                        .FluentMappings.AddFromAssemblyOf())
                    .BuildSessionFactory();
            }

            return _factory;
        }

        public static ISession OpenSession() {
            ISession session;
            session = GetFluentFactory().OpenSession();
            if (session == null) {
                throw new InvalidOperationException("Call to factory.OpenSession() returned null.");
            }
            return session;
        }
    }
}

1 个答案:

答案 0 :(得分:5)

通常的方法是创建一个只允许单一访问的互斥锁(可能在您的公共方法中)。见http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx

未经测试编译,但类似:

    private static Mutex _sessionMutex = new Mutex();

    public static ISession OpenSession() {
        ISession session;

        _sessionMutex.WaitOne();

        session = GetFluentFactory().OpenSession();
        if (session == null) {
            throw new InvalidOperationException("Call to factory.OpenSession() returned null.");
        }

        _sessionMutex.ReleaseMutex();
        return session;
    }