在C#中,可以使用SnmpSharpNet庫來實現SNMP的異步操作。以下是實現異步操作的基本步驟:
using SnmpSharpNet;
using System.Threading.Tasks;
public async Task<SnmpV2Packet> GetAsync(string ipAddress, string communityString, List<Variable> variables)
{
var target = new UdpTarget((IPAddress)new IpAddress(ipAddress), 161, 2000, 1);
var version = VersionCode.V2;
var community = new OctetString(communityString);
var pdu = new Pdu(PduType.Get);
foreach (var variable in variables)
{
pdu.VbList.Add(variable);
}
var result = await Task.Run(() =>
{
var response = (SnmpV2Packet)target.Request(pdu, new UserTarget(version, (OctetString)community));
return response;
});
return result;
}
await
關鍵字:var ipAddress = "192.168.1.1";
var communityString = "public";
var variables = new List<Variable>
{
new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")), // sysDescr
new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.5.0")) // sysName
};
var response = await GetAsync(ipAddress, communityString, variables);
Console.WriteLine(response.Pdu().VbList[0].Data.ToString()); // output sysDescr
Console.WriteLine(response.Pdu().VbList[1].Data.ToString()); // output sysName
通過以上步驟,您可以在C#中實現SNMP的異步操作。