I have an asmx web service that should only be allowed to respond to 1 client at once.
In otherwords if the service is getting called by client A, and server B calls, I would like B to pend until A is finished then B can get serviced.
If this is too complicated then at bare minimum calls from B should fail with a user defined error during the time A is engaging the service.
The reason is that the service relies heavily on IO operations and XML serialization, so it is crucial that the service does not get called simultaneously by more than 1 client.
Thanks in advance
Create a static object that you call lock() on. The
lock()statement will prevent other calls from executing the code inside until the first execution that got the lock completes.Note that depending on your timeout settings B might fail with a timeout depending on how long A takes to complete.
Update: Yes you can use the Monitor class in place of
lock(). You could use the Monitor.TryEnter() method to check if the object is already locked or not (ie: if you wanted to return an error instead of waiting).More details:
From http://msdn.microsoft.com/en-us/library/aa664735(VS.71).aspx:
A lock statement of the form
where x is an expression of a reference-type, is precisely equivalent to
From http://msdn.microsoft.com/en-us/library/de0542zz.aspx:
Use Enter to acquire the Monitor on the object passed as the parameter. If another thread has executed an Enter on the object, but has not yet executed the corresponding Exit, the current thread will block until the other thread releases the object.
So it’s just by design that the code knows to block and not skip. You could skip if you wanted by using the Monitor.TryEnter() method.