user interface - C# Ping.Send causing GUI to freeze -
first time using stackoverflow i'll try best.
i making little app ping servers, issue i'm having gui of program locks while waits response. have far, button_click "ping ip" button, ping_box textbox contain response time, ip_address ip address in form of string.
private void button_click(object sender, routedeventargs e) { stopwatch s = new stopwatch(); s.start(); while (s.elapsed < timespan.fromseconds(2)) { using (ping p = new ping()) { ping_box.text = (p.send(ip_address, 1000).roundtriptime.tostring() + "ms\n"); if (ping_box.text == "0ms\n") { ping_box.text = "server offline or exceeds 1000ms."; } } } s.stop(); }
so in current state pings ip address repeatedly 2 seconds , puts response time textbox, during time gui locks though. need recorrect want textbox response time update each ping (if response time 500 ms textbox should update 4 times).
i've tried use ping.sendasync not work, pointers or appreciated :)
i think should help... can modify further per needs
private void button1_click(object sender, eventargs e) { autoresetevent waiter = new autoresetevent(false); ipaddress ip = ipaddress.parse("192.168.1.2"); var pingsender = new ping(); pingsender.pingcompleted += pingcompletedcallback; pingsender.sendasync(ip, 1000, waiter); } private void pingcompletedcallback(object sender, pingcompletedeventargs e) { // if error occurred, display exception user. if (e.error != null) { messagebox.show(string.format("ping failed: {0}", e.error.tostring()), "error", messageboxbuttons.ok, messageboxicon.error); // let main thread resume. ((autoresetevent)e.userstate).set(); } displayreply(e.reply); // let main thread resume. ((autoresetevent)e.userstate).set(); } public void displayreply(pingreply reply) { if (reply == null) return; ping_box.text = string.format("ping status: {0}, roundtrip time: {1}", reply.status, reply.roundtriptime.tostring()); }
Comments
Post a Comment