WebConnectionGroup.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. //
  2. // System.Net.WebConnectionGroup
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2003 Ximian, Inc (http://www.ximian.com)
  8. //
  9. using System;
  10. using System.Collections;
  11. using System.Net.Configuration;
  12. using System.Net.Sockets;
  13. namespace System.Net
  14. {
  15. class WebConnectionGroup
  16. {
  17. ServicePoint sPoint;
  18. string name;
  19. ArrayList connections;
  20. Random rnd;
  21. public WebConnectionGroup (ServicePoint sPoint, string name)
  22. {
  23. this.sPoint = sPoint;
  24. this.name = name;
  25. connections = new ArrayList (1);
  26. }
  27. public WebConnection GetConnection ()
  28. {
  29. WebConnection cnc = null;
  30. lock (connections) {
  31. WeakReference cncRef = null;
  32. // Remove disposed connections
  33. int end = connections.Count;
  34. ArrayList removed = null;
  35. for (int i = 0; i < end; i++) {
  36. cncRef = (WeakReference) connections [i];
  37. cnc = cncRef.Target as WebConnection;
  38. if (cnc == null) {
  39. if (removed == null)
  40. removed = new ArrayList (1);
  41. removed.Add (i);
  42. }
  43. }
  44. if (removed != null) {
  45. for (int i = removed.Count - 1; i >= 0; i--)
  46. connections.RemoveAt ((int) removed [i]);
  47. }
  48. cnc = CreateOrReuseConnection ();
  49. }
  50. return cnc;
  51. }
  52. WebConnection CreateOrReuseConnection ()
  53. {
  54. // lock is up there.
  55. WebConnection cnc;
  56. WeakReference cncRef;
  57. int count = connections.Count;
  58. for (int i = 0; i < count; i++) {
  59. WeakReference wr = connections [i] as WeakReference;
  60. cnc = wr.Target as WebConnection;
  61. if (cnc == null) {
  62. connections.RemoveAt (i);
  63. count--;
  64. continue;
  65. }
  66. if (cnc.Busy)
  67. continue;
  68. return cnc;
  69. }
  70. if (sPoint.ConnectionLimit > count) {
  71. cnc = new WebConnection (this, sPoint);
  72. connections.Add (new WeakReference (cnc));
  73. return cnc;
  74. }
  75. if (rnd == null)
  76. rnd = new Random ();
  77. int idx = (count > 1) ? rnd.Next (0, count - 1) : 0;
  78. cncRef = (WeakReference) connections [idx];
  79. cnc = cncRef.Target as WebConnection;
  80. if (cnc == null) {
  81. cnc = new WebConnection (this, sPoint);
  82. connections.RemoveAt (idx);
  83. connections.Add (new WeakReference (cnc));
  84. }
  85. return cnc;
  86. }
  87. public string Name {
  88. get { return name; }
  89. }
  90. }
  91. }