I am working on writing a really simple RPC library using C# and sockets for a class assignment. I have the send feature working which is nice but I am testing how my KillServer function works. I have implemented a lot of threading in the Server library and I am not sure that I have gotten down the proper way of canceling and softly killing the threads.
My StartServerThread method:
public void StartServer()
{
ServerThread = new Task(()=>
{
_Socket.Listen(100);
// Enter a loop waiting for connection requests
// Or because I am RDM I don't need connections
while (!_TokenSource.IsCancellationRequested)
{
try
{
var newClient = _Socket.Accept();
_Clients.Add(newClient, ClientThread(newClient));
}
catch (OperationCanceledException)
{
Debug.WriteLine("Canceled");
}
}
foreach (var client in _Clients)
{
client.Key.Disconnect(false);
}
},_TokenSource.Token, TaskCreationOptions.LongRunning);
ServerThread.Start();
}
My problem here is once the thread hits the _Socket.Accept() line it is blocking. So even if I call Cancel on the TokenSource the thread is still stuck at that line and doesn't nicely end. I am having a hard time designing this library in such a way that uses threading and allows good performance with multiple clients connected.