您不需要滚动自己的端口查找逻辑 - 如果您将其指定为 0,Windows 将选择一个空闲端口。然后您可以通过询问调度程序找出分配了哪个端口,如下所示:
// Specify port 0, this will cause Windows to choose a free port
var baseUri = new Uri("net.tcp://" + Dns.GetHostEntry("").HostName + ":0");
host = new WebServiceHost(typeof(MyService));
var endPoint = host.AddServiceEndpoint(typeof(IMyService), new NetTcpBinding(), baseUri);
// Tell WCF to actually bind to a free port instead of 0
endPoint.ListenUriMode = ListenUriMode.Unique;
host.Open();
// Now that the host has bound to a specific port, we can find out which one it chose
return host.ChannelDispatchers.First().Listener.Uri;