public void StartMonitoringNewNode(string name, IPingable node) { lock (monitoredNodes) { monitoredNodes[name] = new MonitoredNode(name, node); } }
private bool Ping(MonitoredNode node, long timeOut) { //var cancelTokenSource = new CancellationTokenSource(); //var cancelToken = cancelTokenSource.Token; var task = Task.Run(() => { var success = false; long millis = 0; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); while (!success && millis < timeOut) { //Console.WriteLine("starting ping..."); try { node.Ping(); var action = new Action(node.Ping); var handler = action.BeginInvoke(null, null); if (handler.AsyncWaitHandle.WaitOne((int)timeOut)) { success = true; } else { Console.WriteLine("Ping time out"); } //node.Ping(); } catch (Exception e) { Console.WriteLine("fail ping: " + e.Message); } millis = stopWatch.ElapsedMilliseconds; } //Console.WriteLine($"success ping, took {millis} ms. max is {timeOut}"); return(millis < timeOut); }); var result = task.Result; return(result); }