Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure an asmx web service only gets called once at a time?

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

like image 973
JL. Avatar asked Mar 07 '10 18:03

JL.


People also ask

Is Asmx web service obsolete?

If you can work with WCF then yes the ASMX services are obsolete because the WCF can fully replace them with more performance and flexibility (multiple binding), functionality.

Does Asmx use soap?

ASMX provides the ability to build web services that send messages using the Simple Object Access Protocol (SOAP). SOAP is a platform-independent and language-independent protocol for building and accessing web services.

Can one Web service call another?

A web service application can also call another web service.


1 Answers

static object _LockObject = new object();

void WebServiceCall()
{
    lock(_LockObject)
    {
        // Do work...
    }
}

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

lock (x) ...

where x is an expression of a reference-type, is precisely equivalent to

System.Threading.Monitor.Enter(x);
try {
   ...
}
finally {
   System.Threading.Monitor.Exit(x);
}

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.

like image 183
Cory Charlton Avatar answered Sep 28 '22 20:09

Cory Charlton