Search code examples
c#wcfnamed-pipesinter-process-communicat

Client checking if named pipe host is open


I have a self-hosted WCF service host and client both on the same machine. I've used WCF here for inter-process communication purposes. I am able to open the host and have the client connect to it after a period of time like so:

ServiceHost host = new ServiceHost(typeof(AIEngineLoader));

string hostAddress = string.Format("net.pipe://localhost/AIEngine/" + name);
var endPointBinding = new NetNamedPipeBinding();
endPointBinding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
endPointBinding.ReceiveTimeout = TimeSpan.MaxValue;
host.AddServiceEndpoint(typeof(IAIEngineLoader), endPointBinding, hostAddress);            

host.Open();

The host is run inside another console app. The client is able to connect to this host after waiting for some time after starting the console process(three seconds now). I don't want to have to wait a prespecified amount of time and then connect to the host. One way could be a blocking wait in a loop while catching the CreateChannel exception in the client. This solution is not elegant. Is there a way for a client to check whether or not a host is listening without resorting to exception catching?


Solution

  • WCF will not simply tell you if someone is listening on that pipe address. The actual name of the pipe is obfuscated, you can only try to connect and catch the exception. You could leave WCF out of the equation by using a named global mutex, this is raw inter-process communication. However, WCF with pipes is itself IPC, so I wouldn't complicate matters with mutexes. It's like sending a postal mail along with a FedEx package to let the other party know that the package is on the way.