我需要调用TcpListener.Stop()? [英] Do I need to call TcpListener.Stop()?

查看:276
本文介绍了我需要调用TcpListener.Stop()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个单独的线程(任务)首先运行应用程序启动,不应该结束,直到应用程序关闭时该代码:

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

TcpListener tcpListener = new TcpListener(IPAddress.Any, port);

tcpListener.Start();

while (true)
{
    TcpClient client = tcpListener.AcceptTcpClient();

    Task.Factory.StartNew(HandleClientCommunication, client);
}

在这种情况下,是否有必要调用的TCPListener。停止()?该线程运行应用程序的整个过程,如果我确实需要调用它,在那里我会这么做?监听器是本地的此主题。而不是有一个,而(真)循环会我有一个而(appRunning)循环,并设置appRunning为假该事件的FormClosing?然后while循环后,我可以叫 tcpListener.Stop()

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

然而,就是它甚至需要调用 TcpListener.Stop(),因为应用程序已在该点以来已经关闭,我使用任务过程结束呢?

However, is it even necessary to call TcpListener.Stop() because the application has already closed at that point and since I'm using Tasks the process ends as well?

推荐答案

尝试这样的事情:

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){                    
            }
        }
    }
}

办法不是因为你必须这么好使用 Thread.sleep代码(毫秒)或类似的东西 - 会有客户端之间的一些延迟接受(睡眠毫秒为单位),那是不好的。

Approach with TcpListener.Pending() is not so good because you must use Thread.Sleep(miliseconds) or something like that - there will be some delay between clients accept(miliseconds in sleep), thats bad.

这篇关于我需要调用TcpListener.Stop()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆