Is ISession thread-safe?

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

Another thread-safety question :-). Is how the ISession instance is handled thread-safe? See:

Thanks in advance!

Dec 29, 2011 at 10: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?

Jan 6, 2012 at 5: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?

Jan 6, 2012 at 8:38 AM
Edited Jan 6, 2012 at 8: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?

Jan 6, 2012 at 4: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 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.

Jan 6, 2012 at 4: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?

Jan 6, 2012 at 4:57 PM

Looks like you;re attempting to recreate async requests.

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

Jan 6, 2012 at 6:24 PM

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