简体   繁体   English

C#中的多线程服务器实现

[英]Multithreaded Server implementation in C#

I'm creating a Windows Service which has a component which listen's to a named pipe to interact with programs run from userspace. 我正在创建一个Windows服务,该服务具有一个组件,该组件侦听命名管道以与从用户空间运行的程序进行交互。 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. 我已经将此答案中的代码用作多线程服务器实现的基础,但是在紧密循环中调用ProcessNextClient操作会产生强烈的代码味道,如下所示。 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? 除了重复捕获IOException并重试外,真的没有更好的方法知道何时将另一个流的开口添加到命名管道吗?

    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
        }
    }

You could defer to WCF to handle the pipes? 您可以服从WCF处理管道吗? 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. 当将新连接建立到应用程序中时,使用IO完成端口通知应用程序代码的中断驱动系统将使您受益。

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. 如果只需要通过将管道的绑定更改为TCP / http绑定,而需要将应用程序带到一个以上的节点上,那么花心思实现WCF还将使您能够扩展一台机器。

An example implementation of a WCF service is here . 这里是WCF服务的示例实现 It also shows how you could host the same service on pipes or on TCP. 它还显示了如何在管道或TCP上托管相同的服务。

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. 您可以随时添加一个断点进行检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM