// 设置取消回调,来兼容老的api async Task <int> PingAsync(CancellationToken cancellation) { var ping = new Ping(); // 这些回调会轮流保持Ping对象的生命,为了避免内存及资源的溢出,当不再需要回调时,必须丢弃回调注册 using var _ = cancellation.Register(() => ping.Cancel()); //设置取消的回调 return(await Task.FromResult(1)); }
private static void RunPing() { try { _ping1 = ExternalLib.Request.Ping(new string[] { "2.16.840.1.114416.0.57513008" }); RequestStatusChangedItem item = _ping1.Execute(TimeSpan.FromSeconds(30)); if (null == item) { _ping1.Cancel(); } } catch (Exception ex) { Console.WriteLine("RunPing: " + ex.Message); } }