ASP.NET MVC Strugging to wrap my head around Async and Task

I currently have a Synchronous method that works fine but runs slowly, it looks like this:

 public ActionResult BroadbandDiagnostics(string Company) { var BroadbandsToTest = db.tbl_broadband.Where(c => c.Company == Company).Where(d => d.Device_Type.Contains("Router")).ToList(); List<BroadbandDiagnostics> listBroadbandDiagnostics = new List<BroadbandDiagnostics>(); foreach (var ipToPing in BroadbandsToTest) { BroadbandDiagnostics broadbanddiagnostics = new BroadbandDiagnostics(); Ping ping = new Ping(); PingReply pingreply = ping.Send(ipToPing.External_IP); broadbanddiagnostics.ExternalIPAddress = ipToPing.External_IP; broadbanddiagnostics.Company = Company; broadbanddiagnostics.PingReplyTime = pingreply.RoundtripTime.ToString(); broadbanddiagnostics.PingStatus = pingreply.Status.ToString(); listBroadbandDiagnostics.Add(broadbanddiagnostics); } return PartialView("_BroadbandDiagnostics", listBroadbandDiagnostics); } 

Now this runs slowly, especially if I have 25 IPs to pass to it. I know what I need to do is make this Async in someway so that it does all the pings at the same time, but everything I have tried so far has failed.

Any guidance would be appreciated on the simplest way to do this and still return my own custom list as above.

by TNTGav via /r/csharp

Leave a Reply