1

I want to uses Isessions from nhibernate over multiple Threads. I read here how to instanciate a factory and it should be threadsafe. I know ISession is not threadsafe, but I am intending of using only one ISession per thread.

Doing this doesnt work:

[Test]
public void TestMultipleThreads(){
  object id;
  using(var session = NHibernateHelper.OpenSession()){
   id = session.Save(new SomeThing("SomeText"));
  };
  Parallel.For(0,2,() =>{
    using (var session =NHibernateHelper.OpenSession()){
       using (var tx=session.BeginTransaction()){
        var something = session.Load<SomeThing>(id);
        Console.WriteLine(something.Text);
      };
    };
  });
}

I cant get that test to running, so that it will print out 2 Names. I am using SQLite and a memory database. What do I miss?

If this is not working, how Should I tell different Threads to use their own session?

EDIT

I get the message from the First Thread and the second throws an exception with Table not Found.

EDIT 2

I think the Prolem lies with the creation of the database. When I create the new Table with a new created session, my other session doesnt know about the other session. But I'll try with an other database.

new SchemaExport(config).Execute(true,true,false,session.Connection,null);
1
  • Your code is legimate. It should be related to sqlite. Try with another DB Commented Jul 25, 2014 at 8:32

1 Answer 1

1

This is most likely because you are using SQLite in memory database, usually it cease to exist when you close the connection,

in this example, it seems like your database is destroyed when you dispose the first session, along with the data you have persisted.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.