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/