views:

27

answers:

0

I have created a single threaded Windows application which communicates with more than 100 sockets (using AsyncCallbacks), may be 5-10 sockets in a sec.

The application works fine when I launch from .NET IDE. The application seems to be hanged if launched from executable. On further research I found that application is communicating on the sockets perfectly fine, only the data on the UI is not refreshed. It seems application is toooo busy to read from the sockets than to refresh UI.

Application works fine on replacing AsyncCallback with an individual thread for each socket but this does no seem to be a good approach.

I tried creating message queues but it did not help.

Am I correct in saying that application is busy reading on the socket than refreshing UI? How can I resolve this issue?

Code I use for AsynCallBack is mentioned below.

    private void ConnectSocket()
    {
        IPEndPoint ipEnd = new IPEndPoint(_ip, _port);
        m_socket = new Socket(ipEnd.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        m_socket.Blocking = false;
        m_socket.ReceiveBufferSize = RECEIVE_BUFFER_SIZE;
        m_socket.NoDelay = true;
        m_socket.LingerState = new LingerOption(false, 0);

        AsyncCallback onconnect = new AsyncCallback(OnConnect);
        m_socket.BeginConnect(ipEnd, onconnect, m_socket);
    }

    private void OnConnect(IAsyncResult ar)
    {
        Socket sock = (Socket)ar.AsyncState;
        try
        {
            sock.EndConnect(ar);
            if (sock.Connected)
            {
                SetupReceiveCallback(sock);
            }
        }
        catch (Exception ex)
        {
        }
    }

    private void SetupReceiveCallback(Socket sock)
    {
        try
        {
            AsyncCallback receiveData = new AsyncCallback(ReceiveData);
            sock.BeginReceive(receivedBuffer, 0, receivedBuffer.Length,
                SocketFlags.None, receiveData, sock);
        }
        catch (SocketException ex)
        {
        }
        catch (Exception ex)
        {
        }
    }

    private void ReceiveData(IAsyncResult ar)
    {
        Socket sock = (Socket)ar.AsyncState;
        try
        {
            int numBytesReceived = sock.EndReceive(ar);

            if (numBytesReceived > 0)
            {
                if (OnReceivedData != null)
                {
                    OnReceivedData(receivedBuffer);
                }
            }
            SetupReceiveCallback(sock);
        }
        catch (SocketException ex)
        {
            //If error code is 1054 then socket connection is terminated from the client.
        }
        catch (Exception ex)
        {
        }
    }