WebConnection CreateOrReuseConnection (HttpWebRequest request)
{
// lock is up there.
WebConnection cnc;
WeakReference cncRef;
int count = connections.Count;
for (int i = 0; i < count; i++) {
WeakReference wr = connections [i] as WeakReference;
cnc = wr.Target as WebConnection;
if (cnc == null) {
connections.RemoveAt (i);
count--;
i--;
continue;
}
if (cnc.Busy)
continue;
PrepareSharingNtlm (cnc, request);
return cnc;
}
if (sPoint.ConnectionLimit > count) {
cnc = new WebConnection (this, sPoint);
connections.Add (new WeakReference (cnc));
return cnc;
}
if (rnd == null)
rnd = new Random ();
int idx = (count > 1) ? rnd.Next (0, count - 1) : 0;
cncRef = (WeakReference) connections [idx];
cnc = cncRef.Target as WebConnection;
if (cnc == null) {
cnc = new WebConnection (this, sPoint);
connections.RemoveAt (idx);
connections.Add (new WeakReference (cnc));
}
return cnc;
}