I'm using SharpSNMP (8.5, the latest version from NuGet) asynchronously to poll a device. It's pretty easy and working apparently fine but there's one thing I can't figure out even from looking at the source code for SharpSnmpLib: Where the type of the object supplied to the callback method is specified.
For example:
Here I crate a new SNMP GET request and call BeginGetResponse.
var message = new GetRequestMessage(RequestCounter.NextId, VersionCode.V2, community, oids);
var udpSocket = SNMPAddress.GetSocket();
// pass my GetRequestMessage as the state object
var v = message.BeginGetResponse(SNMPAddress, new UserRegistry(), udpSocket, new AsyncCallback(HandlePollCompletion), message);
The method message.BeginGetResponse is defined in the SnmpMessageExtension class and ultimately calls BeginReceive on the socket (following snippet is from the SharpSNMP code):
public static IAsyncResult BeginGetResponse(this ISnmpMessage request, IPEndPoint receiver, UserRegistry registry, Socket udpSocket, AsyncCallback callback, object state)
{
// ** code snipped from example for readability **
var ar = udpSocket.BeginReceive(buffer, 0, bufferSize, SocketFlags.None, callback, state);
return new SnmpMessageAsyncResult(ar, udpSocket, registry, receiver, buffer);
}
This returns a SnmpMessageAsyncResult object but this is never passed to the call to udpSocket.BeginReceive so I can't see how it then can later turn up passed to the callback method.
When the reply comes in, my handler method HandlePollCompletion is called:
private void HandlePollCompletion(IAsyncResult ar)
{
// grab handle to original message
GetRequestMessage message = (GetRequestMessage)ar.AsyncState;
// end the async call
try
{
var response = message.EndGetResponse(ar);
}
catch (Exception ex) {}
// process reply here
}
If I put a breakpoint in, I can see the object ar that is passed to HandlePollCompletion(IAsyncResult ar) has the type SnmpMessageAsyncResult.
But as far as I can see, HandlePollResult(IAsyncResult ar) is called by the socket i.e. not from within SharpSNMP.
So by what mechanism is the object passed to HandlePollCompletion(IAsyncResult ar) a SnmpMessageAsyncResult? Perhaps I don't understand the async model as well as I thought I did..
Thanks for your insight, Giles.
Generally speaking, you don't need to care much about that.
Begin/End pair is now obsolete and you should use the Async method with async/await.