Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I really locking this stuff

The environment: 3 web services 2 in the same pool 1 in a different application pool.

They all have the same code trying to access something that is not thread safe say a file that they write to.

I try and lock this code the same way for each web service. I'm not sure if the lock keyword is doing what I want.

One lock I try is this in each web service:

string stringValue
lock (stringValue)

The other lock I try is:

lock (typeof(MyWebServiceClass))

Will these locks prevent any simultaneous writes to the file while it is in use? In this case there are multiple clients hitting each of these web services.

like image 626
zachary Avatar asked Dec 16 '22 12:12

zachary


1 Answers

You need a named Mutex to lock on across application pools /processes:

The C# lock keyword is syntactic sugar for Monitor.Enter(), Monitor.Exit() method calls in a try/finally block. Monitor is a light weight (fully managed) synchronization primitive for in-process locking.

A Mutex on the other hand can be either local or global (across processes on the same machine) - global mutexes, also called named mutexes, are visible throughout the operating system, and can be used to synchronize threads in multiple application domains or processes. Also see MSDN.

like image 153
BrokenGlass Avatar answered Jan 03 '23 05:01

BrokenGlass