Thread Problem

29/11/2006 - 18:39 por JC | Informe spam
Hi People,

Please I need your help.

This code run a thread ok but Not close later.

thanks...

private void RunServer(int aPortNumber)
{
_listener = new TcpListener(IPAddress.Any, aPortNumber);
_listener.Start();

_ServerThread = new Thread(delegate()
{
AcceptClients();
}
);
_ServerThread.Start();
}

public void Close()
{

_ThreadRun = false;

}


public void AcceptClients()
{
while (_ThreadRun)
using (TcpClient client = _listener.AcceptTcpClient())
{
if (client.Connected)
{
NetworkStream stream = client.GetStream();
byte[] data = new byte[1024];
stream.Read(data, 0, data.Length);
string request = Encoding.ASCII.GetString(data);

..
}

}
 

Leer las respuestas

#1 Dave Sexton
29/11/2006 - 19:56 | Informe spam
Hi,

That is because _listener.AcceptTcpClient() is blocking the thread. Setting
_ThreadRun to false isn't going to do anything until
_listener.AcceptTcpClient() returns.

Since there doesn't seem to be any error handling code in place, you won't
be able to end the background thread gracefully. Calling _listener.Stop()
will close the listener, causing AcceptTcpClient to stop blocking, however
an exception will be thrown. Setting _ThreadRun would be pointless in that
case, although it's possible that setting _ThreadRun may cause the loop to
exit if it's set after _listener.AcceptTcpClient() returns and before the
loop restarts, but you shouldn't count on that.

Try the following code instead:

while (true)
{
try
{
using (TcpClient client = _listener.AcceptTcpClient())
{
if (client.Connected)
{
NetworkStream stream = client.GetStream();
byte[] data = new byte[1024];
stream.Read(data, 0, data.Length);
string request = Encoding.ASCII.GetString(data);
}
}
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.Interrupted)
return;
else
throw;
}
}

Dave Sexton

"JC" wrote in message
news:
Hi People,

Please I need your help.

This code run a thread ok but Not close later.

thanks...

private void RunServer(int aPortNumber)
{
_listener = new TcpListener(IPAddress.Any, aPortNumber);
_listener.Start();

_ServerThread = new Thread(delegate()
{
AcceptClients();
}
);
_ServerThread.Start();
}

public void Close()
{

_ThreadRun = false;

}


public void AcceptClients()
{
while (_ThreadRun)
using (TcpClient client = _listener.AcceptTcpClient())
{
if (client.Connected)
{
NetworkStream stream = client.GetStream();
byte[] data = new byte[1024];
stream.Read(data, 0, data.Length);
string request = Encoding.ASCII.GetString(data);

..
}

}

Preguntas similares