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.