/// <summary>Returns at most the 4 closest addresses in order.</summary>
protected List <Connection> GetClosest(List <Connection> cons)
{
List <Connection> closest = new List <Connection>(cons);
// Since MeasuredLatency could change the duration of our sorting we make
// a copy as necessary
Dictionary <Connection, double> latencies = new Dictionary <Connection, double>();
Comparison <Connection> comparer = delegate(Connection x, Connection y) {
double lat_x, lat_y;
if (!latencies.TryGetValue(x, out lat_x))
{
lat_x = _ncservice.GetMeasuredLatency(x.Address);
latencies[x] = lat_x;
}
if (!latencies.TryGetValue(y, out lat_y))
{
lat_y = _ncservice.GetMeasuredLatency(y.Address);
latencies[y] = lat_y;
}
// Remember that smaller is better but -1 is bad...
// If either is smaller than 0 invert the comparison..
if (lat_x < 0 || lat_y < 0)
{
return(lat_y.CompareTo(lat_x));
}
else
{
return(lat_x.CompareTo(lat_y));
}
};
closest.Sort(comparer);
if (closest.Count > 4)
{
closest.RemoveRange(4, closest.Count - 4);
}
return(closest);
}