What's the better way to terminate the following thread?
-
What's the better way to terminate the following thread? 1. Method:
...
public void WaitForClient()
{
while (true)
{
try
{
Socket s = listener.AcceptClient(); // this blocks!
...
// do something!
...
}
catch (Exception)
{
break;
}
}
}
...
static void Main(string[] args)
{
listener = new TcpListener(8002);
listener.Start();
...
thread = new Thread(new ThreadStart(WaitForClient));
thread.IsBackground = true;
thread.Start();
...
// do something!
...
listener.Stop(); // stop listening!
thread.Join(); // wait until the thread is terminated!
...
}2. Method:
...
public void WaitForClient()
{
while (true)
{
Socket s = listener.AcceptClient(); // this blocks!
...
// do something!
...
}
}
...
static void Main(string[] args)
{
listener = new TcpListener(8002);
listener.Start();
...
thread = new Thread(new ThreadStart(WaitForClient));
thread.IsBackground = true;
thread.Start();
...
// do something!
...
thread.Abort(); // abort the thread!
listener.Stop(); // stop listening!
...
}Daniel ;) --------------------------- Never change a running system!
-
What's the better way to terminate the following thread? 1. Method:
...
public void WaitForClient()
{
while (true)
{
try
{
Socket s = listener.AcceptClient(); // this blocks!
...
// do something!
...
}
catch (Exception)
{
break;
}
}
}
...
static void Main(string[] args)
{
listener = new TcpListener(8002);
listener.Start();
...
thread = new Thread(new ThreadStart(WaitForClient));
thread.IsBackground = true;
thread.Start();
...
// do something!
...
listener.Stop(); // stop listening!
thread.Join(); // wait until the thread is terminated!
...
}2. Method:
...
public void WaitForClient()
{
while (true)
{
Socket s = listener.AcceptClient(); // this blocks!
...
// do something!
...
}
}
...
static void Main(string[] args)
{
listener = new TcpListener(8002);
listener.Start();
...
thread = new Thread(new ThreadStart(WaitForClient));
thread.IsBackground = true;
thread.Start();
...
// do something!
...
thread.Abort(); // abort the thread!
listener.Stop(); // stop listening!
...
}Daniel ;) --------------------------- Never change a running system!
I would suggest a third method. Use a variable to flag the thread that it needs to stop working. Then in your thread (presumably in a loop) check for the flag at regular intervals and bail out cleanly. This is probably better handled by an Event object, but I haven't used them in C# as of yet. In a simple scenario a flag variable should do.