If you do in the console, it works normally (code 1), and if it does not output for a form (code 2, 3). What to do here?
public static void PingMethod() { var urles = new List<string> ( Properties.Resources.proxylist.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries) ); var goodUrls = new List<string>(); var badUrls = new List<string>(); var timeout = 1; var sync = new object(); var counter = urles.Count; var isReady = new ManualResetEvent(false); foreach (var ur in urles) { var _url = ur.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries); var u = _url[0]; var url = u; var ping = new Ping(); ping.PingCompleted += (s, e) => { lock (sync) { ping.Dispose(); if (e.Reply.Status == IPStatus.Success) { goodUrls.Add(ur); } else { badUrls.Add(url); } if (--counter == 0) { isReady.Set(); } } }; ping.SendAsync(u, timeout, null); } isReady.WaitOne(); Console.WriteLine("Good Urls"); foreach (var u in goodUrls) { Console.WriteLine(u); } Console.WriteLine(""); Console.WriteLine("Bad Urls"); foreach (var u in badUrls) { Console.WriteLine(u); } Console.WriteLine("goodUrls " + goodUrls.Count); Console.WriteLine("badUrls " + badUrls.Count); Console.ReadKey(); }
For forms, a similar method:
public static List<string> PingTwoMethod() { List<string> urles = new List<string>(Properties.Resources.proxylist_at_15_10_2015.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)); List<string> goodUrls = new List<string>(); List<string> badUrls = new List<string>(); int timeout = 1; Object sync = new object(); int counter = urles.Count; ManualResetEvent isReady = new ManualResetEvent(false); foreach (var ur in urles) { string[] _url = ur.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries); string u = _url[0]; string url = u; Ping ping = new Ping(); ping.PingCompleted += (s, e) => { lock (sync) { ping.Dispose(); if (e.Reply.Status == IPStatus.Success) { goodUrls.Add(url); } else { badUrls.Add(url); } if (--counter == 0) { isReady.Set(); } } }; ping.SendAsync(url, timeout, null); List<string> good = new List<string>(goodUrls); return good; } //isReady.WaitOne(); return goodUrls; }
and a button on the form:
private void button1_Click(object sender, EventArgs e) { List<string> goods = new List<string>(); goods = Pings.PingMethod(); if (goods != null) { foreach (var item in goods) { richTextBox1.Text += item; } } else { richTextBox1.Text += "Пусто"; } }