C # ManualResetEvent

1

What does the ManualResetEvent connectDone serve in the code below? If I use it, when running the main thread hangs, as I am using this code inside the Unity3D (game engine) it locks the whole process and this can not occur.

What is the real need to use it? What's the use?

//static ManualResetEvent connectDone = new ManualResetEvent(false);
static ManualResetEvent sendDone = new ManualResetEvent(false);
static ManualResetEvent receiveDone = new ManualResetEvent(false);

public static void Connect() 
{
    string ServerIP = "127.0.0.1";
    int ServerPort  = 5902;
    try
    {
        EndPoint remoteEP = new IPEndPoint(IPAddress.Parse(ServerIP), ServerPort);
        Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,  ProtocolType.Tcp);
        clientSocket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), clientSocket);
        //connectDone.WaitOne();
    }
    catch (Exception e)
    {
        Debug.LogError(e.ToString());
    }

}

private static void ConnectCallback(IAsyncResult ar) 
{
    try 
    {
        // Retrieve the socket from the state object.
        Socket client = (Socket) ar.AsyncState;

        // Complete the connection.
        client.EndConnect(ar);

        Debug.Log("Socket connected to " + client.RemoteEndPoint.ToString());

        // Signal that the connection has been made.
        //connectDone.Set();
    } 
    catch (Exception e) 
    {
        Debug.LogError(e.ToString());
    }
}
    
asked by anonymous 10.06.2014 / 17:47

1 answer

3

In the case of ManualResetEvent is being used as a flag flag so that the Connect(...) method only returns after the connection has been established.

Since you have ManualResetEvent to block the method there are no benefits in using an asynchronous call. It would be simpler and easier to keep changing the code to:

socket.Connect(...);

In this case the method would be retained in this synchronous call and would only advance after the connection was established.

If you need the code to run asynchronously you can, as you did, remove the ManualResetEvent or use:

socket.ConnectAsync(...);
    
10.06.2014 / 18:33