Multi-thread console application built with S# repositories (outside ASP.NET context)

115 views
Skip to first unread message

Claudio Maccari

unread,
Aug 4, 2009, 1:52:19 PM8/4/09
to sharp-arc...@googlegroups.com
I hope this is not OT.

I have some troubles with a multi-thread application that use S# repositories
My application is not a web application (I'm outside ASP.NET) . It's a
windows service.

I've wrote this simple console application in order to reproduce my scenario.
Here is the code:

class Program
{
static IRepository<Customer> repository = new Repository<Customer>();

static void Main(string[] args)
{
NHibernateInitializer.Instance().InitializeNHibernateOnce(
() => InitializeNHibernateSession());


System.Console.WriteLine("Waiting....");
ThreadPool.QueueUserWorkItem(DoSomeQueries);
ThreadPool.QueueUserWorkItem(DoSomeQueries);
System.Console.ReadLine();
}

private static void DoSomeQueries(object state)
{
var r = new Random();
int limit = r.Next(100, 150);
for (int i = 0; i < limit; i++)
{
IList<Customer> customers = repository.GetAll();
Thread.Sleep(r.Next(1000, 2000));
System.Console.WriteLine("Customer {0} on thread {1}",
customers[0], Thread.CurrentThread.ManagedThreadId);
}
}

private static void InitializeNHibernateSession()
{
NHibernateSession.Init(
new SimpleSessionStorage(),
new string[] { "Northwind.Data.dll" },
new AutoPersistenceModelGenerator().Generate(),
"NHibernate.config");
}
}


If I use only one thread (comment one of two lines with
ThreadPool.QueueUserWorkItem(DoSomeQueries); ) it works fine.
If I use two threads it fails after the first query.

What should I do in order to handle thread concurrency correctly ?
Many thanks.
claudio

ps.
As you can see my sample is written on top of S# Northwind sample (RTM version).
Once it's ok could be included in the main sample if someone else is
interested in.
--
Claudio Maccari
--------------------------------
http://testdrivendevelopment.wordpress.com/

Simone Busoli

unread,
Aug 5, 2009, 4:18:41 PM8/5/09
to sharp-arc...@googlegroups.com
NHibernate sessions are not thread safe, you need a different session storage.

David Archer

unread,
Aug 11, 2009, 2:37:33 PM8/11/09
to S#arp Architecture
Claudio,

I posted a code sample in a previous thread about this:

http://groups.google.com/group/sharp-architecture/browse_thread/thread/51794671c91bc5e9/386efc30d4c0bf16#386efc30d4c0bf16

Basic idea is to use a per-thread variable to store the session.

HTH,

David Archer
Reply all
Reply to author
Forward
0 new messages