3

I would like to lock("on some object") to block two threads of a single user to access some part of the code in the same time. Two differents users with two differents sessions can do that. I am using FormsAuthentication for handling sessions. What kind of object can I use for the lock ? Does this class (FormsAuthentication) supply some kind of singletons for each session, or do you know some other trick to do that?

I am thinking about handling a singleton hiding a dictionnary on a set of objects (as set of locks for different opened session). But before starting such complexe class that could make code less understandable, am I forgetting some best and easyer way to do that?

Do you know some better trick to do that lock for a signle session ?

minchiya
  • 603
  • 1
  • 7
  • 13

1 Answers1

2

If you can create a string that is unique to the single session that you want to block, you could use a Named Mutex.

After you have created a Mutex, a thread can call WaitOne() to acquire the mutex (thereby blocking any other threads that subsequently call `WaitOne()).

Then the thread can call ReleaseMutex() to free it up and allow another thread waiting in WaitOne() to continue.

Some sample code for a Console app:

string mutexName = "Some name unique to the session";

bool created;
Console.WriteLine("Press RETURN to create mutex.");
Console.ReadLine();

using (var mutex = new Mutex(initiallyOwned:false, name:mutexName, createdNew: out created))
{
    Console.WriteLine("Attempting to enter mutex");
    mutex.WaitOne();
    Console.WriteLine("Got mutex. Press RETURN to release.");
    Console.ReadLine();
    mutex.ReleaseMutex();
    Console.WriteLine("Released mutex. Press RETURN to exit.");
    Console.ReadLine();
}

Note that this also works across processes. It does use up an operating system event handle, so it might be overkill if you have hundreds of sessions. It also, as Marc notes below, assumes "sticky" load balancing.

Community
  • 1
  • 1
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • @MarcGravell Out of interest, would you ever need to lock across system boundaries? That would read as a code smell to me. – Gusdor Nov 18 '13 at 13:23
  • @Gusdor that depends on what you are doing, and how you are defining "system" ;p – Marc Gravell Nov 18 '13 at 13:24
  • @MarcGravell, very good point. I had issues with something similar when infrastructure changed that up on us as well. The WF architecture is a good example of an architecture that is "sticky sessions" agnostic. At this point, I've kind of started moving that direction myself with new designs. – Mike Perrenoud Nov 18 '13 at 13:25
  • @MarcGravell a succinct counterpoint! Substitute system for machine :D – Gusdor Nov 18 '13 at 13:27
  • 2
    Purely for info: for the SE network, on the **rare** occasions we need this, we use redis as a lock arbiter, via `SET {key} {token} EX {timeout} NX` – Marc Gravell Nov 18 '13 at 13:27