Ehs*_*san 15 .net c# multithreading named-pipes
嗨,
我想使用NamedPipeServerStream,这是.NET 3.5中用于namedpipe通信的新功能.我想写多线程管道服务器.它是默认处理还是我应该为此编写代码.我的管道服务器应该一次处理多个请求
任何解决方案或代码?
Bri*_*ndy 25
您可以通过重复创建NamedPipeServerStream并等待一个连接来编写多线程管道服务器,然后为该NamedPipeServerStream实例生成一个线程.
根据下面链接的.NET MSDN文档,您只能拥有254个并发客户端.对于Win32 API,您可以根据系统资源传递特殊值以获得无限制.似乎MSDN文档是错误的,如下所述.
以下代码未经过测试,因此请不要简单地复制和粘贴以供生产使用而不进行测试:
public class PipeServer
{
bool running;
Thread runningThread;
EventWaitHandle terminateHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
public string PipeName { get; set; }
void ServerLoop()
{
while (running)
{
ProcessNextClient();
}
terminateHandle.Set();
}
public void Run()
{
running = true;
runningThread = new Thread(ServerLoop);
runningThread.Start();
}
public void Stop()
{
running = false;
terminateHandle.WaitOne();
}
public virtual string ProcessRequest(string message)
{
return "";
}
public void ProcessClientThread(object o)
{
NamedPipeServerStream pipeStream = (NamedPipeServerStream)o;
//TODO FOR YOU: Write code for handling pipe client here
pipeStream.Close();
pipeStream.Dispose();
}
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
}
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*son 20
每个NamedPipeServerStream实例都是一个Stream实现,它包含一个命名管道实例的句柄.您可以(以及多线程管道服务器)为同一命名管道提供多个NamedPipeServerStream实例:每个实例都将句柄包装到命名管道的不同实例,为不同的客户端提供服务.命名管道实例(即使对于同一管道)由操作系统保持独立,因此不需要任何显式编码来保持每个客户端与服务器的通信分离.
您需要明确编码的是服务器的线程模型.在这个SO答案中解释了对服务器进行多线程处理的最简单方法,其中包括一个伪代码模板.如果需要支持大量并发调用者,则可扩展的实现将使用线程池和异步方法,而不是为每个连接创建专用线程.