This question is a follow-up to a previous question that I had asked:
How to Perform Multiple "Pings" in Parallel using C#
I was able to get the accepted answer (a Windows console application) to work, but when I tried to run the code in a Windows forms application, the following code will freeze on the line containing Task.WaitAll(pingTasks.ToArray())
. Here is the code that I am trying to run:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.NetworkInformation;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
List<String> addresses = new List<string>();
for (Int32 i = 0; i < 10; ++i) addresses.Add("microsoft.com");
List<Task<PingReply>> pingTasks = new List<Task<PingReply>>();
foreach (var address in addresses)
{
pingTasks.Add(PingAsync(address));
}
//Wait for all the tasks to complete
Task.WaitAll(pingTasks.ToArray());
//Now you can iterate over your list of pingTasks
foreach (var pingTask in pingTasks)
{
//pingTask.Result is whatever type T was declared in PingAsync
textBox1.Text += Convert.ToString(pingTask.Result.RoundtripTime) + Environment.NewLine;
}
}
private Task<PingReply> PingAsync(string address)
{
var tcs = new TaskCompletionSource<PingReply>();
Ping ping = new Ping();
ping.PingCompleted += (obj, sender) =>
{
tcs.SetResult(sender.Reply);
};
ping.SendAsync(address, new object());
return tcs.Task;
}
}
}
Does anyone have any ideas as to why it's freezing?