我对例外有所了解,但不知道如何解决。我的大多数并发线程将使用 SaveOrUpdate 来定位相同的对象图。那么我可以在任何时候只打开一个会话吗?如果是这样,我如何在多个线程上强制执行?
public class FnhManagerTS
{
private static Configuration cfg;
private static ISessionFactory sessionFactory;
private static string connectionString;
[ThreadStatic]
private static ISession _session = null;
private FnhManagerTS() { }
private static ISession OpenSession()
{
// Create a database connection and open a ISession on it.
return sessionFactory.OpenSession();
}
/// <summary>
/// ThreadStatic ISession.
/// </summary>
/// <returns></returns>
public static ISession Session()
{
if (_session != null && _session.IsOpen)
return _session;
else
{
_session = OpenSession();
return _session;
}
}
回购:
public class GenericRepoTS<T>
where T : class
{
private ISession session;
public GenericRepoTS()
{
this.session = FnhManagerTS.Session();
}
public void SaveOrUpdate(IList<T> instances)
{
if (instances != null)
{
using (ITransaction transaction = session.BeginTransaction())
{
try
{
lock (instances)
{
foreach (var i in instances)
{
session.SaveOrUpdate(i);
}
transaction.Commit();
}
}
catch (Exception ex)
{
transaction.Rollback();
Trace.TraceError("GenericRepository.SaveOrUpdate IList<" + typeof(T).ToString() + "> ", ex.ToString());
}
}
}
}