Domanda

I'm creating a Windows Service which has a component which listen's to a named pipe to interact with programs run from userspace. I've used the code from this answer as a base for a multithreaded server implementation, however I get strong code smell from the ProcessNextClient action being called in a tight loop, reproduced below. Is there really no better way to know when an opening for another stream is to be added to the named pipe than to repeatedly catch an IOException and try again?

    public void ProcessNextClient()
    {
        try
        {
            NamedPipeServerStream pipeStream = new NamedPipeServerStream(PipeName, PipeDirection.InOut, 254);
            pipeStream.WaitForConnection();

            //Spawn a new thread for each request and continue waiting
            Thread t = new Thread(ProcessClientThread);
            t.Start(pipeStream);
        }
        catch (Exception e)
        {//If there are no more avail connections (254 is in use already) then just keep looping until one is avail
        }
    }
È stato utile?

Soluzione

You could defer to WCF to handle the pipes? You would benefit from an interrupt driven system using IO Completion Ports to notify your application code when new connections were made into the application.

Taking the pain of implementing WCF would also give you the ability to scale off one machine if you need to take your application over more than one node just by changing the binding from a pipe to a TCP/http binding.

An example implementation of a WCF service is here. It also shows how you could host the same service on pipes or on TCP.

Altri suggerimenti

It looks to me like the the code will sit at

pipeStream.WaitForConnection();

until a client is detected and then continue. I don't think it's looping it like you described unless it's being hammered with clients. You could always add a breakpoint to check.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top