lextudio / sharpsnmplib

Sharp SNMP Library- Open Source SNMP for .NET
https://sharpsnmp.com
MIT License
356 stars 152 forks source link

ISnmpMessage.BeginGetResponse/EndGetResponse pair doesn't work in Task.FromAsync. #242

Closed lextudio-support closed 3 hours ago

lextudio-support commented 3 hours ago

The Begin/EndGetResponse pair in SnmpMessageExtension doesn't work in Task.FromAsync. It throws a cast exception at runtime: trying to cast an OverlappedAsyncResult to a SnmpMessageAsyncResult.

The problem lies in SnmpMessageExtension.BeginGetResponse:

Method TaskFactory.FromAsync internally wraps the EndXXX method into an AsyncCallback and uses this callback as the AsyncCallback argument in the BeginXXX method. In SharpSNMP 7.0 implementation, the EndGetResponse actually extects an IAsyncResult of type SnmpMessageAsyncResult. But the callback in line531 receives an IAsyncResult from Socket.BeginReceive which is of type OverlappedAsyncResult. Thus, a cast exception will be thrown at runtime.

One possible fix is to wrap the BeginGetResponse's AsyncCallback argument before it's passed to the socket's BeginReceive method. Add the following before calling updSocket.BeginReceive works in my environment:

        if(callback != null)
        {
            callback= (asyncResult)=>
            {
                var result = new SnmpMessageAsyncResult(asyncResult, udpSocket,registry,receiver,buffer);
                callback(result);
            };
        }

Thanks.

Original Reported Date: 2012-04-28T01:19:18.973-07:00 Planned For Release: BigDipper Refresh (7.5) Original CodePlex ID: 7234

lextudio-support commented 3 hours ago

Copied from CodePlex without authors:

Just fixed as you suggested in master,

https://github.com/lextm/sharpsnmplib/tree/4063362075917c3b91e1a6f31b577b8ea2a0fd06

Can you do further testing and confirm that it works?

Thanks, Lex

Original Posted Date: 2012-04-28T23:27:45.197-07:00

lextudio-support commented 3 hours ago

Copied from CodePlex without authors:

Just confirmed the fix works. Thanks.

Original Posted Date: 2012-05-01T20:37:26.387-07:00

lextudio-support commented 3 hours ago

Already part of 7.5 RC2.

Original Closed Date: 2012-05-02T23:16:18.41-07:00