The Problem
I've created a thread in c# (on windows 10), which asks a server for some data:
- Such a thread should be created each time the user enters a certain menu (
mainMenuJoinRoomButtonClick()) - It should be closed each time the users exits that menu (we exit with
roomListBackButtonClick())
This is done in order for us to save resources and prevent errors which occur if the thread isn't closed. (please see the code below)
I tried using threadName.Abort() but it gives me the following error:
System.PlatformNotSupportedException: 'Thread abort is not supported on this platform.'
I also tried threadName.Interrupt() which produces this error (the error occurs in the line: Thread.Sleep(3000);):
System.Threading.ThreadInterruptedException: 'Thread was interrupted from a waiting state.'
What is the problem here and how can I close the thread?
Research Done
Looking around the internet has showed there is no good way to abort a thread, is that so?
I also found this answer (first one) which uses Thread.sleep() but this doesn't seem like a real solution because it doesn't release the thread's resources, and I'm unsure how to implement this solution in my code.
The Code
namespace TriviaClient
{
public partial class MainWindow : Window
{
public const int GET_ROOMS_REQUEST = 92;
public Thread refreshRoomsListThread;
public static NetworkStream clientStream;
public MainWindow()
{
StartClient();
InitializeComponent();
}
public void refreshRoomList()
{
while (true)
{
this.Dispatcher.Invoke((Action)(() =>
{
roomsListErrorBox.Text = "";
}));
serializeAndSendMessage(GET_ROOMS_REQUEST, "");
Dictionary<string, object> response = receiveAndDeserializeMessage();
if (response.ContainsKey("status") && (string)response["status"] == "1")
{
this.Dispatcher.Invoke((Action)(() =>
{
roomsList.Items.Clear();
}));
Dictionary<int, string> rooms = new Dictionary<int, string>();
JArray Jrooms = (JArray)response["rooms"];
foreach (JArray room in Jrooms)
{
rooms.Add((int)room[0], (string)room[1]);
}
foreach (KeyValuePair<int, string> roomInDict in rooms)
{
this.Dispatcher.Invoke((Action)(() =>
{
roomsList.Items.Add(new Label().Content = $"{roomInDict.Key}: {roomInDict.Value}");
}));
}
}
else if (response.ContainsKey("message"))
{
this.Dispatcher.Invoke((Action)(() =>
{
roomsListErrorBox.Text = (string)response["message"];
}));
}
Thread.Sleep(3000);
}
}
private void roomListBackButtonClick(object sender, RoutedEventArgs e)
{
refreshRoomsListThread.Abort();
}
private void mainMenuJoinRoomButtonClick(object sender, RoutedEventArgs e)
{
roomsListErrorBox.Text = "";
refreshRoomsListThread = new Thread(refreshRoomList);
refreshRoomsListThread.Start();
}
}
}