C# Manualresetevent

Asked

Viewed 119 times

1

What good is the code below the Manualresetevent connectDone? If I use it, when running the main thread hangs, as I am using this code within the Unity3d(game engine) it hangs the entire process and this cannot occur.

What is the real need to use it? What is the point?

//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());
    }
}

1 answer

3


In the event that the ManualResetEvent is being used as a signal flag so that the method Connect(...) return only after the link has been established.

Given that it has the ManualResetEvent to block the method there are no benefits in using an asynchronous call. It would be simpler and easy to keep changing the code to:

socket.Connect(...);

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

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

socket.ConnectAsync(...);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.