"PiotrKolodziej" <pi*************@gmail.com> wrote:
I have a simple question. Here is the code related to my question:
while (true)
{
if (tcpListenerServer.Pending() && !this.Disposing)
{
This forms a busy polling loop, which will waste CPU resources and will
starve other processes and threads. It's better to call a method which
will block (possibly with a timeout). After every timeout, you can then
check if the listening thread should be shut down. For example, check
out Socket.Poll() with SelectMode.SelectRead. You can get the listening
socket behind the TcpListener from its Server property.
Alternatively, you can cancel the blocking call to AcceptTcpClient by
calling Stop() on the server on a different thread. For example:
---8<---
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
class App
{
static void Main()
{
TcpListener server = new TcpListener(2000);
ManualResetEvent serverRunning = new ManualResetEvent(false);
Thread serverThread = new Thread(delegate()
{
server.Start();
serverRunning.Set();
try
{
for (;;)
{
TcpClient client = server.AcceptTcpClient();
}
}
catch (SocketException ex)
{
// Blocking interrupted
}
});
serverThread.Start();
// prevent race to server.Stop() before server.Start()
serverRunning.WaitOne();
Console.Write("Press Enter to stop listening...");
Console.ReadLine();
server.Stop();
serverThread.Join();
}
}
--->8---
TcpClient tcpClient =
tcpListenerServer.AcceptTcpClient();
downloadThreadClass obj = new
downloadThreadClass(tcpClient.GetStream());
Thread myThread = new Thread(new
ThreadStart(obj.downloadThreadFunction));
myThread.Start();
}
}
TcpClient object returned by AccepTcpClient is destroyed right after program
leaved 'if' block.
The variable called 'tcpClient' goes out of scope, but the object it
references (on the managed heap) is not disposed of.
before program do this, i'am passing NetworkStream from tcpClient to the
thread which is proceeding some task on this stream.
The question is will it work? The stream is retreved but tcpClient will not
exist during operations on this stream.
The NetworkStream object (from TcpClient.GetStream()) keeps a reference
to the backing socket (i.e. TcpClient.Client), so it keeps it alive from
GC and finalization.
That said, you should dispose of the underlying socket or TcpClient or
an owning NetworkStream when it's done with it (closing/disposing either
of TcpClient or a NetworkStream constructed to own the stream will also
dispose of the socket; TcpClient.GetStream() creates an owning
NetworkStream).
The documentation for TcpClient.Close() says that it does not close the
underlying connection, but it is wrong: .NET Reflector shows that it
does in fact close the connection.
-- Barry
--
http://barrkel.blogspot.com/