WebConnectionGroup.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. static ConnectionManagementData manager;
  21. Random rnd;
  22. public WebConnectionGroup (ServicePoint sPoint, string name)
  23. {
  24. this.sPoint = sPoint;
  25. this.name = name;
  26. connections = new ArrayList (1);
  27. }
  28. public WebConnection GetConnection ()
  29. {
  30. WebConnection cnc = null;
  31. lock (connections) {
  32. WeakReference cncRef = null;
  33. // Remove disposed connections
  34. int end = connections.Count;
  35. ArrayList removed = null;
  36. for (int i = 0; i < end; i++) {
  37. cncRef = (WeakReference) connections [i];
  38. cnc = cncRef.Target as WebConnection;
  39. if (cnc == null) {
  40. if (removed == null)
  41. removed = new ArrayList (1);
  42. removed.Add (i);
  43. }
  44. }
  45. if (removed != null) {
  46. for (int i = removed.Count - 1; i >= 0; i--)
  47. connections.RemoveAt ((int) removed [i]);
  48. }
  49. cnc = CreateOrReuseConnection ();
  50. }
  51. return cnc;
  52. }
  53. WebConnection CreateOrReuseConnection ()
  54. {
  55. // lock is up there.
  56. WebConnection cnc;
  57. WeakReference cncRef;
  58. int count = connections.Count;
  59. if (sPoint.ConnectionLimit > count) {
  60. cnc = new WebConnection (this, sPoint);
  61. connections.Add (new WeakReference (cnc));
  62. return cnc;
  63. }
  64. if (rnd == null)
  65. rnd = new Random ();
  66. foreach (WeakReference wr in connections) {
  67. cnc = wr.Target as WebConnection;
  68. if (cnc.Busy)
  69. continue;
  70. return cnc;
  71. }
  72. int idx = (count > 1) ? rnd.Next (0, count - 1) : 0;
  73. cncRef = (WeakReference) connections [idx];
  74. cnc = cncRef.Target as WebConnection;
  75. if (cnc == null) {
  76. cnc = new WebConnection (this, sPoint);
  77. connections.RemoveAt (idx);
  78. connections.Add (new WeakReference (cnc));
  79. }
  80. return cnc;
  81. }
  82. public string Name {
  83. get { return name; }
  84. }
  85. }
  86. }