Поведение не так, как ожидалось. Если появятся новые запросы, когда текущий из них занят, он выбрасывает ошибку «доступ к пути», пока не будет выпущена текущая поток выполнения.
Код: Выделить всё
using Newtonsoft.Json;
using System;
using System.IO;
using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Threading;
namespace API.PipeServer
{
public class Server
{
private bool running;
private Thread runningThread;
private EventWaitHandle terminateHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
public string PipeName { get; set; }
private 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)
{
using (NamedPipeServerStream pipeStream = (NamedPipeServerStream)o)
{
StreamReader sr = new StreamReader(pipeStream);
//Receive instruction message
string instructionJson = sr.ReadLine();
Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: --- Receiving Instruction ---");
Console.WriteLine(instructionJson);
//Getting instruction message
var instruction = JsonConvert.DeserializeObject(instructionJson);
//Get data
var json = API.API.GetAPIJson(instruction);
//Send data back to Python client
try
{
pipeStream.Write(Encoding.UTF8.GetBytes(json));
pipeStream.WaitForPipeDrain();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: --- Closing Stream ---");
pipeStream.Close();
pipeStream.Dispose();
}
}
public void ProcessNextClient()
{
try
{
Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: Creating server");
PipeSecurity pipeSecurity = new PipeSecurity();
pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow));
var pipeStream = NamedPipeServerStreamAcl.Create("test_api", PipeDirection.InOut, 254, PipeTransmissionMode.Message, PipeOptions.None, 1024, 1024, pipeSecurity);
pipeStream.WaitForConnection();
//Spawn a new thread for each request and continue waiting
Thread t = new Thread(ProcessClientThread);
t.Start(pipeStream);
}
catch (Exception e)
{
Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: Error - {e.Message}");
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/730 ... ipe-server