sanchop22
sanchop22

Reputation: 2809

Thread stops working suddenly in C#

I have a multi-threaded app (TCPListener). There is a thread that looks to a list of requests and sends data if a request is avaliable in the list. The code is shown below:

private void HandleClientRequestsTask()
{
    try
    {
        while (true)
        {
            if (ClientRequests.Count > 0)
            {
                ClientRequest ActiveClientRequest = ClientRequests.First();

                int DataLen = ActiveClientRequest.CommPacket.PacketStr.Length;
                int TxDataLen = 0;

                try
                {
                    TxDataLen = ActiveClientRequest.CommPacket.TCPClient.Client.Send(ConvertPacketToRawData(ActiveClientRequest.CommPacket.PacketStr));
                }
                catch (Exception ex)
                {
                    AddLog(LogIndex.TCPClientNotExist, ex.ToString());
                }

                if (DataLen != TxDataLen)
                    AddLog(LogIndex.TCPClientDataSendErr, ActiveClientRequest.CommPacket.TCPClient.Client.RemoteEndPoint.ToString(), ActiveClientRequest.CommPacket.CmdType, ActiveClientRequest.CommPacket.RXDevID.ToString());

                ClientRequests.Remove(ActiveClientRequest);
            }

            Thread.Sleep(HANDLE_CLIENT_REQ_TASK_SLEEP_VALUE);
        }
    }
    catch (Exception ex)
    {
        AddLog(LogIndex.UnhException, ex.ToString());
    }
}

The thread above stops suddenly, I think. When I put a debug point on the if (ClientRequests.Count > 0) line, the program doesn't stop and the breakpoint never gets hit. When I pause debug and look at the threads window, thread doesn't seen.

Where do you think the problem lies? I think, the thread stops running at any time.

Upvotes: 0

Views: 3717

Answers (1)

ABCD
ABCD

Reputation: 907

If you really need two try-catch blocks move the outer try-catch inside the while loop.

I know it started because i saw some data on client side. Is there a possibility to stop the thread if an exception is caught?

Yes, if it jump to the outer catch block thread won't execute while loop any more.

Upvotes: 4

Related Questions