I'm running a WCF service, and calling ServiceHost's Open() method will raise an AddressAlreadyInUseException if the adress is ..err .. already in use !
Is there a way to test whether the address is available without raising an exception?
I'm running a WCF service, and calling ServiceHost's Open() method will raise an AddressAlreadyInUseException if the adress is ..err .. already in use !
Is there a way to test whether the address is available without raising an exception?
The addresses being used by the ServiceHost are listed in ServiceHost.BaseAddresses. You could potentially check there, prior to making your call.
Alternatively, just try to open the service, and catch and handle the AddressAlreadyInUseException gracefully. If you receive that, you know it's in use, and you can move on to your secondary logic.
You might try a little known feature of WCF endpoint configurations: ListenUriMode.Unique. Skonnard has a really good write-up about this: http://www.pluralsight.com/community/blogs/aaron/archive/2006/04/24/22610.aspx
I don't know if this will handle your current scenario (I don't know if it will detect the collision and whether or not you are ok with it spooling up on a different address), but it just might.
This also might not be a feasible solution if you have no central way of communicating endpoint addresses to your clients (database, etc). WS-Discovery will have a way of getting around this limitation, but you'd have to wait till .NET 4.0 or use one of the open source implementations for WCF 3.5.
You can't.
Consider the code:
if( AddressIsFree( addr ) )
{
OpenServiceOn( addr );
}
What happens if something else registers the port in that fraction of a second between your check, and when you open the service? It's a race condition.
The correct way to handle this is to just try to open the port, and catch the exception if it fails, and do something to compensate. Exceptions aren't bad. They exist, in part, for this exact reason. There's no reason to try and do lots of checking to make sure than an exception will not be thrown - in most cases, just try the operation, and catch the exception if it occurs.
They're usually not even much more code.