User1969772734 posted
I am hoping to reach out to the community today for some "best practices" guideance.
I currently have 7 WCF hosts that have been written that are supposed so host the WCF service on any available port within a specified range. We have a function that finds an available port within the OS and returns it to the host having already been reserved
using the "bind" method.
My question with the following code is:
1) With all services coming through this same "FindAvailablePort" process, do we need a mutex as coded below?
2) Is there any chance of a race condition?
Dim portMutex As Mutex = ObtainNamedMutex("MyMutexName" & Guid.NewGuid().Tostring())
'returns a new mutex with a unique name for all seven services.
Try
portMutex.WaitOne()
Dim endPoint As New IPEndPoint(IPAddress.Any, 0)
Using socket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
socket.Bind(endPoint)
Dim local As IPEndPoint = DirectCast(socket.LocalEndPoint, IPEndPoint)
Return local.Port
End Using
Finally
portMutex.ReleaseMutex()
End Try