Is ISession thread-safe?

Topics: Core, Writing modules
Developer
Dec 25, 2011 at 10:55 PM

Another thread-safety question :-). Is how the ISession instance is handled thread-safe? See: https://forum.hibernate.org/viewtopic.php?f=25&t=984397&view=previous

Thanks in advance!

Developer
Dec 29, 2011 at 11:08 AM

As when spawning off more than two background threads I have similar errors than described here, may it be that it's not thread-safe?

Coordinator
Jan 6, 2012 at 6:00 AM

Again, I'm not sure I'm following. The unit of work is the request. Each request is associated with a single thread from beginning to end. So why exactly would ISession need to be thread-safe?

Developer
Jan 6, 2012 at 9:38 AM
Edited Jan 6, 2012 at 9:38 AM

Again my mental model could be wrong (about what ISession does too), but: I'd like two or more background threads spawned off from a controller action read the database concurrently. (I know this implies that the work done is IO-bound and using threads is wrong; actually it is CPU-bound, but some database access does happen.) Is this safe?

Coordinator
Jan 6, 2012 at 5:01 PM

That is a completely different question. If you use a thread to do more than respond to the current request, you risk clogging of the asp.net thread pool. If you spawn a new thread, well, let's just say that the mess you just created is yours to clean ;)

Under normal circumstances, each request is running in the same thread from start to finish (not taking async into account here but we don't support it at the moment anyway) and nothing else is running on that thread, so you don't have to worry about thread safety on request-scoped objects. That's always been the case in ASP.NET and I think it's also true of all modern web platforms.

Developer
Jan 6, 2012 at 5:49 PM

No, the threads (actually not raw threads but Tasks, so there would be less mess to clean :-)) would also be used to deliver the response, so all threads would be waited to complete before the action returns. I yet have to learn whether the specific example I'm doing would hurt throughput in the long run, but it would definitely speed up the loading of a page.

But anyway, is concurrent database access (more precisely, concurrent calls to the same IRepository) in background threads that are tied to a request thread considered dangerous?

Coordinator
Jan 6, 2012 at 5:57 PM

Looks like you;re attempting to recreate async requests.

Each unit of work / request will have its own transaction so no.

Developer
Jan 6, 2012 at 7:24 PM

Something along the lines of that, yes, but with CPU-bound operations. Thanks then!