Do I need to call TcpListener.Stop ()?

I have this code in a separate thread (Task) that starts first when the application starts and should not end before the application closes:

TcpListener tcpListener = new TcpListener(IPAddress.Any, port); tcpListener.Start(); while (true) { TcpClient client = tcpListener.AcceptTcpClient(); Task.Factory.StartNew(HandleClientCommunication, client); } 

In this case, do you need to call tcpListener.Stop() ? This thread runs throughout the life of the application, and if I need to call it, where would I do it? The listener is local to this thread. Instead of having a while (true) , will I have a while (appRunning) and set appRunning to false in the FormClosing event? Then, after the while loop, I could call tcpListener.Stop() .

However, it is even necessary to call tcpListener.Stop() because the application is already closed at this point, and since I use Tasks, does the process also end?

+3
multithreading c #
Sep 19 '11 at 19:24
source share
1 answer

Try something like this:

 public class Listener { private readonly TcpListener m_Listener = new TcpListener(IPAddress.Any, IPEndPoint.MinPort); private CancellationTokenSource m_Cts; private Thread m_Thread; private readonly object m_SyncObject = new object(); public void Start() { lock (m_SyncObject){ if (m_Thread == null || !m_Thread.IsAlive){ m_Cts = new CancellationTokenSource(); m_Thread = new Thread(() => Listen(m_Cts.Token)) { IsBackground = true }; m_Thread.Start(); } } } public void Stop() { lock (m_SyncObject){ m_Cts.Cancel(); m_Listener.Stop(); } } private void Listen(CancellationToken token) { m_Listener.Start(); while (!token.IsCancellationRequested) { try{ var socket = m_Listener.AcceptSocket(); //do something with socket } catch (SocketException){ } } } } 

The approach with TcpListener.Pending() not so good because you have to use Thread.Sleep(miliseconds) or something like that - there will be some delay between receiving clients (miliseconds in sleep), thats bad.

+2
Jul 23 '13 at 17:14
source share



All Articles