Delay in processing command from socket listener
<p>I have a special socket listener, that works in it's thread. It's job to get commands from external program that updates database. When command comes on socket i am calling special method, that updates my application cache from database.</p>

<p>I have a problem, that is delay between sending command from external program and processing that command in my app (ASP .NET Application). Every day my app restarting at 4 a.m. and by the end of the day i have delay about 1-2 hours.</p>

<p>How i can reduce this delay?</p>

<p>You can find code of my listener below.</p>

<p>Thanks.</p>

<pre><code>public delegate void OnECIGetCommand( string command );

public class ECIMain
{

    protected Socket socket;
    protected string ip;
    protected int port;

    private static ECIMain INSTANCE = null;

    const int receivedDataSize = 250;
    protected static byte[] buffer = new byte[ receivedDataSize ];  
    protected static StringBuilder sb;                              

    protected static DoWorkEventHandler onCommand;              

    private ECIMain() 
    {
        socket = new Socket(AddressFamily.InterNetwork, 
                   SocketType.Stream, ProtocolType.Tcp);
        sb = new StringBuilder();
    }

    private void StartSocket()
    {
        sb.Clear();
        socket.Listen(1);
        socket.BeginAccept(null, receivedDataSize, 
               new AsyncCallback(AcceptReceiveDataCallback), socket);
    }

    private static void AcceptReceiveDataCallback(IAsyncResult ar)
    {
        // Get the socket that handles the client request.
        Socket listener = (Socket)ar.AsyncState;

        // End the operation and display the received data on the console.
        byte[] Buffer;
        int bytesTransferred;
        Socket handler = listener.EndAccept(out Buffer, 
                         out bytesTransferred, ar);
        HandleBuff(bytesTransferred, Buffer);

        // Create the state object for the asynchronous receive. 
        handler.BeginReceive(buffer, 0, receivedDataSize, 
                SocketFlags.None, new AsyncCallback(ReadCallback), handler);
    }

    private static void HandleBuff(int size, byte[] buff )
    {
        if (size &gt; 0)
        {
            // There  might be more data, so store the data received so far.
            sb.Append(Encoding.ASCII.GetString(buff, 0, size));

            // Check for end-of-file tag. If it is not there, read more data.
            var content = sb.ToString();
            int pos = -1;
            if ((pos = content.IndexOf("&lt;/cmd&gt;")) &gt; -1)
            {
                // All the data has been read from the 
                // client.
                pos += 6; 
                if( pos &lt; content.Length )
                    content = content.Remove(pos);


                var startPos = content.LastIndexOf("&lt;cmd&gt;");
                if( startPos &gt; -1 ) 
                {
                    if (startPos &gt; 0)       
                            content = content.Remove(0, startPos);
                    BackgroundWorker worker = new BackgroundWorker();
                    worker.DoWork += onCommand;
                    worker.RunWorkerAsync(content);

                }
                sb.Remove(0, pos); 
            }
        }
    }

    private static void ReadCallback(IAsyncResult ar)
    {
        // Retrieve the state object and the handler socket
        // from the asynchronous state object.
        Socket handler = (Socket)ar.AsyncState;
        SocketError error;
        // Read data from the client socket. 
        int bytesRead = handler.EndReceive(ar, out error );

        if (error == SocketError.Success)
        {
            if (bytesRead &gt; 0)
            {
                HandleBuff(bytesRead, buffer);
                handler.BeginReceive(buffer, 0, receivedDataSize,
                        SocketFlags.None, new AsyncCallback(ReadCallback), handler);
            }
            else 
            {
                handler.Disconnect(true);
                INSTANCE.StartSocket();
            }
        }
        else if (error == SocketError.Shutdown || error == SocketError.ConnectionReset)
        {
            INSTANCE.StartSocket();   
        }
    }

    public static string InitECI(int port, DoWorkEventHandler commandHandler)
    {
        if (INSTANCE == null)
        {
            INSTANCE = new ECIMain();
            INSTANCE.port = port;
            onCommand += commandHandler;
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList
                  .FirstOrDefault(a =&gt; a.AddressFamily == AddressFamily.InterNetwork);
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
            INSTANCE.ip = ipAddress.ToString();
            try
            {
                INSTANCE.socket.Bind(localEndPoint);
            }
            catch (System.Net.Sockets.SocketException e)
            {
                if (e.SocketErrorCode == System.Net.Sockets
                                         .SocketError.AddressAlreadyInUse)
                {
                    //INSTANCE.socket.Bind(localEndPoint);
                }
                throw e;
            }
            INSTANCE.StartSocket();
        }
        return INSTANCE.ip;
    }

    public static void ShutDownECI()
    {
        if( INSTANCE.socket.Connected )
            INSTANCE.socket.Disconnect(false);
        INSTANCE.socket.Close();
    }
}
</code></pre>