I really lock this stuff

Environment: 3 web services 2 in one pool 1 in another application pool.

They all have the same code trying to access something that is not thread safe โ€” the file they write.

I am trying to block this code the same way for every web service. I am not sure if the lock keyword does what I want.

One lock I'm trying to make is in every web service:

string stringValue lock (stringValue) 

Another lock attempt:

 lock (typeof(MyWebServiceClass)) 

Will these locks prevent writing to the file at the same time during use? In this case, several clients fall into each of these web services.

+4
source share
2 answers

To block application pools / processes, you need the name Mutex :

The C # lock keyword is syntactic sugar for calls to Monitor.Enter() , Monitor.Exit() in a try/finally block. Monitor - low-weight synchronization primitive (fully controllable) to block the process.

A Mutex , on the other hand, can be either local or global (via processes on one computer) - 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 .

+10
source

I think you need to use Mutex to lock between AppDomains.

In addition, it is worth avoiding type locking. This can often lead to deadlocks if the code tries to block elsewhere after the first lock has been received. It is best to lock an object whose sole purpose is to act as a lock.

For instance:

 object padlock; lock(padlock) { // work here } 
+2
source

All Articles