I am only a beginner in c# and have taken over a project at work which includes code contributed by 2 other developers. There is a memory leak with the code when reading data from sql. Basically the code reads a ping result from the database and returns it into a sparkline which I then display on a dashboard. Hope you can help.
[ActionName("get-response-times")]
public JsonResult GetResponseTime()
{
try
{
//todo...get list of sites we we want to check from database
var entities = new Entities();
var sites = entities.Sites.ToList();
var status = new List<ResponseDataModel>();
foreach (var site in sites)
{
var response = Ping(site.URL);
site.SiteResponseHistories.Add(new SiteResponseHistory
{
CreateDate = DateTime.UtcNow,
ResponseTime = (int)response,
Site = site
});
status.Add(new ResponseDataModel
{
ResponseTime = (int)response,
Name = site.Name,
ID = site.Id,
History = site.SiteResponseHistories.OrderByDescending(a => a.CreateDate).Select(a => a.ResponseTime.GetValueOrDefault(0)).Take(100).Reverse().ToArray()
});
}
entities.SaveChanges();
return Json(status);
}
catch (Exception)
{
// handle if necessary
}
return Json("");
}
protected long Ping(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Timeout = 3000;
request.AllowAutoRedirect = false; // find out if this site is up and don't follow a redirector
request.Method = "HEAD";
Stopwatch watch = new Stopwatch();
watch.Start();
using (var response = request.GetResponse())
{
return watch.ElapsedMilliseconds;
}
}
catch
{
return -1;
}
}