'Multithreaded Client
I created a client-server in C#, and everything works, and I thought of adding the ability to cancel requests that timed out, so at the server-side, each request I send starts a new Timer, and when it runs out of time, I send another request that says ABORT {MessageId}.
This is what I implemented so far, but for some reason, it won't terminate the Thread, when I debugged I saw that it finds the correct thread but doesn't terminate it.
Perhaps there is even a better way for implementing this...
Dictionary<int, Thread> threads = new();
private static void ReceiveResponse()
{
//I get the message (body)
string? response = Util.Bytes2String(body);
if (response == null)
return;
//There is no need to create a new Thread for aborting a Thread...
if (ShouldAbort(response))
return;
Thread thread = new(() =>
{
HandleCommand(response, msgId);
Thread.CurrentThread.IsBackground = true;
});
threads.Add(msgId, thread);
thread.Start();
Console.WriteLine($"Thread {thread.ManagedThreadId} was created for Request No. {msgId}");
}
private static bool ShouldAbort(string command)
{
if (!Util.IsStringValid(command))
return false;
if (command.StartsWith(MessageType.ABORT_TASK))
{
if (int.TryParse(command.Split('\t')[1], out int id)) //Get the ID of the message to abort
{
if (threads.ContainsKey(id))
{
AbortThreadAt(id);
return true;
}
else
Console.WriteLine($"Couldn't abort Request No. {id} because it doesn't exist");
return false;
}
{
Console.WriteLine($"Unable to stop the Thread.");
return true;
}
}
return false;
}
private static void AbortThreadAt(int i)
{
try
{
Thread thread = threads[i];
threads.Remove(i);
Console.WriteLine($"Thread {thread.ManagedThreadId} for Request No. {i} was aborted");
thread.Interrupt();
}
catch (Exception) { }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
