WebConnectionGroup.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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.Configuration;
  12. using System.Net.Configuration;
  13. using System.Net.Sockets;
  14. namespace System.Net
  15. {
  16. class WebConnectionGroup
  17. {
  18. ServicePoint sPoint;
  19. string name;
  20. ArrayList connections;
  21. static ConnectionManagementData manager;
  22. const string configKey = "system.net/connectionManagement";
  23. int maxConnections;
  24. Random rnd;
  25. static WebConnectionGroup ()
  26. {
  27. manager = (ConnectionManagementData) ConfigurationSettings.GetConfig (configKey);
  28. }
  29. public WebConnectionGroup (ServicePoint sPoint, string name)
  30. {
  31. this.sPoint = sPoint;
  32. this.name = name;
  33. connections = new ArrayList (1);
  34. maxConnections = (int) manager.GetMaxConnections (sPoint.Address.Host);
  35. }
  36. public WebConnection GetConnection (string name)
  37. {
  38. WebConnection cnc = null;
  39. lock (connections) {
  40. WeakReference cncRef = null;
  41. // Remove disposed connections
  42. int end = connections.Count;
  43. ArrayList removed = null;
  44. for (int i = 0; i < end; i++) {
  45. cncRef = (WeakReference) connections [i];
  46. cnc = cncRef.Target as WebConnection;
  47. if (cnc == null) {
  48. if (removed == null)
  49. removed = new ArrayList (1);
  50. removed.Add (i);
  51. }
  52. }
  53. if (removed != null) {
  54. for (int i = removed.Count - 1; i >= 0; i--)
  55. connections.RemoveAt ((int) removed [i]);
  56. }
  57. cnc = CreateOrReuseConnection ();
  58. }
  59. return cnc;
  60. }
  61. WebConnection CreateOrReuseConnection ()
  62. {
  63. // lock is up there.
  64. WebConnection cnc;
  65. WeakReference cncRef;
  66. int count = connections.Count;
  67. if (maxConnections > count) {
  68. cnc = new WebConnection (this, sPoint);
  69. connections.Add (new WeakReference (cnc));
  70. return cnc;
  71. }
  72. if (rnd == null)
  73. rnd = new Random ();
  74. foreach (WeakReference wr in connections) {
  75. cnc = wr.Target as WebConnection;
  76. if (cnc.Busy)
  77. continue;
  78. return cnc;
  79. }
  80. int idx = (count > 1) ? rnd.Next (0, count - 1) : 0;
  81. cncRef = (WeakReference) connections [idx];
  82. cnc = cncRef.Target as WebConnection;
  83. if (cnc == null) {
  84. cnc = new WebConnection (this, sPoint);
  85. connections.RemoveAt (idx);
  86. connections.Add (new WeakReference (cnc));
  87. }
  88. return cnc;
  89. }
  90. public string Name {
  91. get { return name; }
  92. }
  93. }
  94. }