Halabella
Halabella

Reputation: 59

How to abort thread that use AcceptTcpClient() inside?

AcceptTcpClient() prevents app from exit after I called thrd.Abort().

How to exit application when in listening?

Upvotes: 4

Views: 5841

Answers (2)

user8838939
user8838939

Reputation: 11

You could:

Use BeginAcceptTcpClient() and End.. instead: See:https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.beginaccepttcpclient(v=vs.110).aspx

Or your could:

Create a TcpClient and send your listener message:

therefore (I guess you have a loop in your thread):

Upvotes: 1

Iridium
Iridium

Reputation: 23721

You should be able to interrupt the call to AcceptTcpClient() by closing the TcpListener (this will result in an exception being thrown by the blocking AcceptTcpClient(). You should not be aborting the thread, which is generally a very bad idea in all but a few very specific circumstances.

Here's a brief example:

class Program
{
    static void Main(string[] args)
    {
        var listener = new TcpListener(IPAddress.Any, 12343);
        var thread = new Thread(() => AsyncAccept(listener));
        thread.Start();
        Console.WriteLine("Press enter to stop...");
        Console.ReadLine();
        Console.WriteLine("Stopping listener...");
        listener.Stop();
        thread.Join();
    }

    private static void AsyncAccept(TcpListener listener)
    {
        listener.Start();
        Console.WriteLine("Started listener");
        try
        {
            while (true)
            {
                using (var client = listener.AcceptTcpClient())
                {
                    Console.WriteLine("Accepted client: {0}", client.Client.RemoteEndPoint);
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine(e);
        }
        Console.WriteLine("Listener done");
    }
}

The code above starts a listener on a separate thread, pressing Enter on the console window will stop the listener, wait for the listener thread to complete, then the application will exit normally, no thread aborts required!

Upvotes: 8

Related Questions