Reputation: 9171
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.
Upvotes: 4
Views: 248
Reputation:
I think you need to use a Mutex to lock between AppDomains.
Also, for what its worth, avoid locking on a type. That can often result in deadlocks if code elsewhere tries to lock after the first lock has been obtained. It's best to lock on an object whose only purpose is to act as a lock.
For example:
object padlock;
lock(padlock)
{
// work here
}
Upvotes: 2
Reputation: 160992
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.
Upvotes: 10