Search code examples
c#tcpclient

Get async result from TCPClient.BeginConnect's callback method


This is my code:

TcpClient _tcpClient = new TcpClient(AddressFamily.InterNetwork);

public void BeginConnect(string address, ushort port, OnConnectCallback cb) {
    IAsyncResult ar = _tcpClient.BeginConnect(address, port, ConnectCallback, cb);
}

private void ConnectCallback(IAsyncResult ar) {
    //The ar is acturally an instance of MultipleAddressConnectAsyncResult
    //it contains the execution result I want. 
    //However, MultipleAddressConnectAsyncResult class is not public.
    _tcpClient.EndConnect(ar);
}

As you know, IAsyncResult has few useful method. I cannot get execution result's detail from it. When I debug this code, I found the things I want as following: enter image description here How can I access the Non-Public members?


Solution

  • You can use reflection in C# to access non public methods. Try the following snippet:

    var errorCode = ar.GetType().GetProperty("ErrorCode", 
    BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic).GetValue(ar);
    

    Basically we reflect on the type we need (type of IAsyncResult via ar) and then specify the field/property we are interested in ("ErrorCode"), and then get its value for a particular instance (ar).

    Similar to GetProperty, there are various helper methods to get values for fields, members etc. which take various filters to get the specific value you need.