Abort the thread, or just let it clean up the computer?
I have the following code, I want to interrupt a thread if it is not completed in 2 seconds. You can see from the first code that I am creating a new myThread evertyime in the while loop and not interrupting it. Well I don't want it to be like this, but if I take myThread outside of the loop and use the abort () function like the second code does. there will be an interrupt error.
while (true)
{
try
{
m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//reset up socket
myThread = new System.Threading.Thread(new System.Threading.ThreadStart(socket_connect));
myThread.Start();
if (!myThread.Join(2000))
{
throw new SocketException(SocketError.AccessDenied);
}
}
catch (Exception ex)
{
m_socket.Close();
}
}
}
private static void socket_connect()
{
m_socket.Connect(remoteEndPoint);//Connect to remote device
}
I tried the following code first, but it gives threadabortexceptions.
myThread = new System.Threading.Thread(new System.Threading.ThreadStart(socket_connect));
while (true)
{ try
{
m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//reset up socket
myThread.Start();
if (!myThread.Join(2000))
{
myThread.Abort();
throw new SocketException(SocketError.AccessDenied);
}
}
catch (Exception ex)
{
m_socket.Close();
}
}
}
private static void socket_connect()
{
m_socket.Connect(remoteEndPoint);//Connect to remote device
}
I know abort () is not a good idea, so I move on to keep the threads remaining and let C # (. Net? I don't know who actually does this) garbage collection related. And can anyone tell if this is a good idea since this program will run on a board that doesn't have a lot of memory to store bundles of threads. And can anyone tell me exactly how garbage collection is done in C #? for example streams. It should also be noted that I do not have a Task class or a socket.beginconnect () method, I think this is because I am building a program that will run on a small board, not a PC. The board is netduido plus and I am building my project on netduino plus platform.
source to share
I have the following code, I want to interrupt a thread if it is not completed in 2 seconds.
Reading the code, it looks like you actually want to try and connect a socket to a resource within two seconds. If more than two seconds have passed, you want to continue.
I am basically reproducing the code in this answer , I believe this is roughly what you should be doing to achieve your goal, rather than twisting the thread and interrupting it:
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
// Connect using a timeout (2 seconds)
IAsyncResult result = socket.BeginConnect( sIP, iPort, null, null );
bool success = result.AsyncWaitHandle.WaitOne( 2000, true );
if ( !success )
{
// NOTE, MUST CLOSE THE SOCKET
socket.Close();
throw new ApplicationException("Failed to connect server.");
}
// Success
//...
source to share
[edit: massive copy doesn't fire on break / space]
Oh please use a library Task
, it's easier to deal with these situations:
(LINQPad-friendly blob)
void Main()
{
var canceller = new CancellationTokenSource();
var task = Task.Factory.StartNew(() => DoStuff(canceller.Token), canceller.Token);
if(!task.Wait(2000, canceller.Token))
{
canceller.Cancel();
task.Wait(2);
}
sw.Elapsed.Dump();
}
private Stopwatch sw;
private void DoStuff(CancellationToken token)
{
try
{
sw = Stopwatch.StartNew();
while(!token.IsCancellationRequested)
{
}
}
// no catch - rethrown exceptions must be checked on Task
finally
{
sw.Stop();
}
}
Alternatively, you can use some kind of "exit flag" condition - bool, which both your thread starter and your thread runner can see and use in their while
state.
source to share