C # Async Socket Client Blocks Main Interface

Another network issue this time is related to the Async Socket Client, which is based on MSDN examples, at least for this initial version. Currently, when the user presses a button on the interface, Async Connect is trying to connect to a network device, the code is shown below -

//Mouse Event handler for main thread
private void btn_Read_MouseDown(object sender, MouseEventArgs e)
{
    Stopwatch sw = Stopwatch.StartNew();
    if (!networkDev.Connected)
        networkDev.Connect("192.168.1.176", 1025);

    if(networkDev.Connected)
       networkDev.getReading();
    sw.Stop();//Time time taken...
}

If the endpoint is enabled and exists on the network, this code works fine (less than one second for the entire operation). However, if the network device is disconnected or inaccessible, the AsyncSocket Connect function keeps the flow of basic forms. Currently, if the device is unavailable, the entire interface is locked for approximately 20 seconds (using a stopwatch). I think I'm blocking because the main thread is waiting for a return in the Connect request, does this mean that I need to put this connection request on another thread?

I have included the code that the Async Socket Box uses, -

    public bool Connect(String ip_address, UInt16 port)
    {
        bool success = false;

        try
        {
            IPAddress ip;
            success = IPAddress.TryParse(ip_address, out ip);
            if (success)
                success = Connect(ip, port);
        }
        catch (Exception ex)
        {
            Console.Out.WriteLine(ex.Message);
        }
        return success;
    }     

    public bool Connect(IPAddress ip_address, UInt16 port)
    {
        mSocket.BeginConnect(ip_address, port, 
           new AsyncCallback(ConnectCallback), mSocket);
        connectDone.WaitOne();//Blocks until the connect operation completes, 
                              //(time taken?) timeout?
        return mSocket.Connected;
    }

    private void ConnectCallback(IAsyncResult ar)
    {
        //Retreive the socket from thestate object
        try
        {
            Socket mSocket = (Socket)ar.AsyncState;
            //Set signal for Connect done so that thread will come out of 
            //WaitOne state and continue
            connectDone.Set();

        }
        catch (Exception ex)
        {
            Console.Out.WriteLine(ex.Message);
        }       
    }

, Async-, , , , , , . , 20 , (, ). , , . , , , , Socket, , AsyncSocket. , , .

+3
2

, , Connect :

mSocket.BeginConnect(ip_address, port, ...);
connectDone.WaitOne(); // Blocks until the connect operation completes [...]

, . BeginConnect, ?

+4

:

connectDone.WaitOne();  //Blocks until the connect operation completes, (time taken?) timeout?
+1

All Articles