问题
Using this tutorial i came up with the code below. My client is ran frequently. Its activated via clicks and possibly can be launched twice at the same moment in certain circumstance. I am worried one client may close while another client opens which causes the pipe to be closed in that slim few milliseconds. Whats the best way to keep the pipe open?
static public void ThreadStartServer()
{
while (true)
{
using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("mytestpipe"))
{
Console.WriteLine("[Server] Pipe created {0}", pipeStream.GetHashCode());
pipeStream.WaitForConnection();
Console.WriteLine("[Server] Pipe connection established");
using (StreamReader sr = new StreamReader(pipeStream))
{
string temp;
while ((temp = sr.ReadLine()) != null)
{
Console.WriteLine("{0}: {1}", DateTime.Now, temp);
}
}
}
}
回答1:
Make your pipe server multi-threaded, with one thread dedicated to listening. See these answers:
来源:https://stackoverflow.com/questions/1689360/best-way-to-keep-a-pipe-open-after-a-remote-close