Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abort thread that use AcceptTcpClient() inside?

Tags:

c#

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

How to exit application when in listening?

like image 652
Halabella Avatar asked Jan 13 '23 13:01

Halabella


2 Answers

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!

like image 97
Iridium Avatar answered Jan 19 '23 01:01

Iridium


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):

  • break the loop wherein the listener.AcceptTcpClient() is running. (i.e. CancelAsync()) from outside and Loop While (!Tread.CancellationPending);

  • Create a TcpClient and send your listener a message (and discard data); TcpClient see: https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient(v=vs.110).aspx

  • Now your thread can go on with: client.close() and listener.stop()
like image 36
user8838939 Avatar answered Jan 19 '23 01:01

user8838939