【发布时间】:2017-01-20 01:24:07
【问题描述】:
我有一个程序用于通过 SNMP 从我的网络获取一些数据。 我使用最后一个 .NET 和 SharpSnmp library。 我实现了this post 中公开的 ForEachAsync 方法。 所以我可以并行执行 snmp 请求(并详细说明响应),为列表中的每个设备创建一个任务。它可以工作,但如果设备由于某种原因没有回复,我的程序就会卡住。 所以我需要管理某种超时来“杀死”库公开的异步函数。 这就是我在 foreachAsync 中调用的函数:
public static async Task<Tuple<string, List<Variable>, Exception>>
GetAsync(string ip, IEnumerable<string> vars, int timeout = 5000)
{
try
{
IPAddress agentIp;
bool parsed = IPAddress.TryParse(ip, out agentIp);
if (!parsed)
{
foreach (IPAddress address in
Dns.GetHostAddresses(ip).Where(address => address.AddressFamily == AddressFamily.InterNetwork))
{
agentIp = address;
break;
}
if (agentIp == null)
throw new Exception("Impossibile inizializzare la classe CGesSnmp senza un indirizzo IP valido");
}
IPEndPoint receiver = new IPEndPoint(agentIp, LOCAL_PORT);
VersionCode version = VersionCode.V2;
string community = "public";
List<Variable> vList = new List<Variable>();
foreach (string s in vars)
vList.Add(new Variable(new ObjectIdentifier(s)));
// This is the function I want to "stop" or "kill" in some way
List<Variable> result = (List<Variable>)await Messenger.GetAsync(version, receiver, new OctetString(community), vList);
return new Tuple<string, List<Variable>, Exception>(ip, result, null);
}
catch (Exception ex)
{
return new Tuple<string, List<Variable>, Exception>(ip, null, ex);
}
}
【问题讨论】:
-
查看是否存在接受 TaskCancellationToken 的方法的变体。
-
我忘了指定。没有!
-
你可以使用this technique包装它。
标签: c# .net async-await