For starters, I only want to be able to READ from the database in multiple threads.
I tried that by using the same session, which fails.
Below is my test code. It is important to know that MyContext is a singleton class which holds one NHibernate Session, and the LocationRepository.GetLocation() method is using MyContext to access an Isession and executing some NHibernate criteria to get information from the database. (not shown below)
Code:
public void NHibernateThreadTest()
{
Thread[] threads = new Thread[10];
ThreadTestUnsafe r = new ThreadTestUnsafe();
// Create the threads
for (int i = 0; i < 10; i++)
{
threads[i] = new Thread(r.ThreadMethod);
ParameterizedThreadStart operation = new ParameterizedThreadStart(r.ThreadMethod);
threads[i] = new Thread(operation);
}
for (int i = 0; i < 10; i++)
{
threads[i].Start(MyContext.Current);
}
// wait till all threads end.
for (int i = 0; i < 10; i++)
{
threads[i].Join();
}
}
class ThreadTestUnsafe
{
private int sharedValue = 0;
protected LocalDataStoreSlot myContextSlot;
/// <summary>
/// ThreadCode gets the specified context.
/// </summary>
/// <param name="context">The context.</param>
internal void ThreadMethod(Object context)
{
// Apply the saved context to the current thread
myContextSlot = Thread.GetNamedDataSlot("MyContext");
Thread.SetData(myContextSlot, context as MyContext);
for (int i = 0; i < 10; i++)
{
// Race condition??
Location location = LocationRepository.GetLocation(188);
NUnitHelper.WriteTraceLine(location.Name);
Thread.Sleep(10);
}
}
}
The important thing is that this fails. If I understand correctly, I should make sure that I will be using different NHibernate Sessions for different threads? I will not be writing but only reading from the database, it should than work?