I have written a C# .NET code that utilizes NamedPipeServerStream to send and receive data. My goal is to ensure that when a client disconnects, the server waits and then establishes a new connection when the client reconnects.
The code seems to work in my initial tests, but since I'm new to this, I'm unsure if I've implemented it correctly. my main concern is with memory leaks, performance, and the way I handle Named Pipes recovery when a client disconnects.
I would greatly appreciate any suggestions or insights on whether this is the proper way to achieve this.
Here's the code I've written:
using System.IO.Pipes;
using System.Text;
namespace Service.IPC;
public class PipeServer
{
private NamedPipeServerStream _pipeServer;
private readonly string _pipeName;
private StreamReader reader;
private Thread readThread;
private bool threadRunning = false;
private readonly ILogger<PWService> _logger;
public event EventHandler<DataEventArgs> DataReceived;
public PipeServer(string pipeName, ILogger<PWService> logger)
{
_logger = logger;
_pipeName = pipeName;
_pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 4, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
_logger.LogInformation("Pipe Name: {pipeName}", pipeName);
}
public void Start()
{
Thread thread = new(async () =>
{
while (true)
{
if (_pipeServer.IsConnected)
{
if (!threadRunning)
{
readThread = new Thread(ReadData)
{
Name = "NamedPipeServerReadThread",
IsBackground = true
};
readThread.Start();
threadRunning = true;
}
}
else
{
if (!threadRunning)
{
_logger.LogInformation("Waiting for connecction...");
await _pipeServer.WaitForConnectionAsync();
_logger.LogInformation("Connected...");
}
else
{
_pipeServer.Dispose();
_pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 4, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
}
}
}
})
{
Name = "NamedPipeServerThread",
IsBackground = true
};
thread.Start();
}
public void Stop()
{
readThread.Interrupt();
_pipeServer.Close();
}
private async void ReadData()
{
byte[] buffer = new byte[1024];
int bytesRead;
while (true)
{
if (_pipeServer.IsConnected)
{
bytesRead = await _pipeServer.ReadAsync(buffer);
if (bytesRead == 0)
break;
string data = Encoding.UTF8.GetString(buffer, 0, bytesRead);
string[] parts = data.Split(',');
if (parts.Length == 2)
{
DataReceived?.Invoke(this, new DataEventArgs { Title = parts[0], Message = parts[1] });
}
}
else
{
break;
}
}
threadRunning = false;
}
public async void Send(string title, string message)
{
try
{
if (_pipeServer.IsConnected)
{
await _pipeServer.WriteAsync(Encoding.UTF8.GetBytes(title + "," + message));
}
}
catch (Exception) { }
}
}
```
Threadinstead ofTask? \$\endgroup\$