tags:

views:

28

answers:

1

Hi All

I implemented a TCP Client using a thread opening a socket to a server and reading data from it in synchronous way. When the line String thisLine = aReadStream.ReadLine(); blocks because there is no data to read from the socket and I try to perform a Thread.Abort to kill the thread ( since it is blocked on that ReadLine() ) I expect to be able to catch a ThreadAbortException BUT I can't.

The thread remains blocked on that ReadLine() and is not killed. Below the code I am using in my Thread.

Do you know why and what I am doing wrong and what to do to unblock that ReadLine()?

private void readSocket_andTriggerEvents()
{            
    TcpClient aClient = null;         

    try
    {
        aClient = new TcpClient();
        aClient.Connect(_HOST, _PORT);
        Trace.WriteLine("Socket Connected");

        NetworkStream aStream = aClient.GetStream();
        StreamReader aReadStream = new StreamReader(aStream);
        int nTimes = 0;

        while (this.isSocketThreadStarted) 
        {

            String thisLine = aReadStream.ReadLine(); // when no data
            // is available the application hangs here.
            // Thread.Abort doesn't work!
           }
    }                
    catch (ThreadAbortException ex)
    {
        Trace.WriteLine("The Thread was brute-forced killed");
        // I never come here!!
    }
    catch (SocketException ex)
    {
        Helper.ShowErrorMessage(ex);
    }
    finally{
        aClient.Close();
        Trace.WriteLine("socket closed");
     }

}
+1  A: 

Close the socket from a different thread. This should throw a SocketException when ReadLine is blocked.

dtb
Thanks for your help! One more thing if you are still around: do you know why ThreadAbortException is not thrown as I expected?
Abruzzo Forte e Gentile
@Abruzzo Forte e Gentile: Sorry, no idea. But using Thread.Abort is not recommended anyway.
dtb
Yes I know, but in this scenario, since I am not using Asynchronous sockets it is the only thing I can do.By the way I discovered by chance if I call first .Abort() and then _socket.Close() the ThradAbortExcepion can be catch.Thanks for you big help!Ciao
Abruzzo Forte e Gentile