I'm currently learning C# and having an issue in running a method on a background thread before reassigning it to a new one (I have a socket that's working in the background that I need to close as I'm getting the Only one usage of each socket address (protocol/network address/port) is normally permitted
exception). I set the tcpThread
to null
and thought it would kill everything inside it but I guess it the socket is still alive in heap.
This is to perform a restart TCP thread action if it hangs.
private static void startTCPServer()
{
viewModel.stopTCPServer(); // I need to be able to call this on the existing tcpThread
tcpThread = null;
tcpThread = new Thread(new ThreadStart(viewModel.startTCPServer));
tcpThread.Priority = ThreadPriority.AboveNormal;
tcpThread.IsBackground = true;
tcpThread.Start();
}
Also, is this the right approach?
EDIT:
Here's using Task
which results in the same issue:
private static void startTCPServer()
{
tokenSource = new CancellationTokenSource();
Task.Run(() =>
{
while (true)
{
if (tokenSource.Token.IsCancellationRequested)
{
viewModel.stopTCPServer();
break;
} else
{
viewModel.startTCPServer();
break;
}
}
}, tokenSource.Token);
}