SocketAsyncResult.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // System.Net.Sockets.SocketAsyncResult.cs
  2. //
  3. // Authors:
  4. // Ludovic Henry <[email protected]>
  5. //
  6. // Copyright (C) 2015 Xamarin, Inc. (https://www.xamarin.com)
  7. //
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.Runtime.InteropServices;
  31. using System.Runtime.Remoting.Messaging;
  32. using System.Threading;
  33. namespace System.Net.Sockets
  34. {
  35. [StructLayout (LayoutKind.Sequential)]
  36. internal sealed class SocketAsyncResult: IOAsyncResult
  37. {
  38. public Socket socket;
  39. public SocketOperation operation;
  40. Exception DelayedException;
  41. public EndPoint EndPoint; // Connect,ReceiveFrom,SendTo
  42. public byte [] Buffer; // Receive,ReceiveFrom,Send,SendTo
  43. public int Offset; // Receive,ReceiveFrom,Send,SendTo
  44. public int Size; // Receive,ReceiveFrom,Send,SendTo
  45. public SocketFlags SockFlags; // Receive,ReceiveFrom,Send,SendTo
  46. public Socket AcceptSocket; // AcceptReceive
  47. public IPAddress[] Addresses; // Connect
  48. public int Port; // Connect
  49. public IList<ArraySegment<byte>> Buffers; // Receive, Send
  50. public bool ReuseSocket; // Disconnect
  51. public int CurrentAddress; // Connect
  52. public Socket AcceptedSocket;
  53. public int Total;
  54. internal int error;
  55. public int EndCalled;
  56. public IntPtr Handle {
  57. get { return socket != null ? socket.Handle : IntPtr.Zero; }
  58. }
  59. /* Used by SocketAsyncEventArgs */
  60. public SocketAsyncResult ()
  61. : base ()
  62. {
  63. }
  64. public void Init (Socket socket, AsyncCallback callback, object state, SocketOperation operation)
  65. {
  66. base.Init (callback, state);
  67. this.socket = socket;
  68. this.operation = operation;
  69. DelayedException = null;
  70. EndPoint = null;
  71. Buffer = null;
  72. Offset = 0;
  73. Size = 0;
  74. SockFlags = SocketFlags.None;
  75. AcceptSocket = null;
  76. Addresses = null;
  77. Port = 0;
  78. Buffers = null;
  79. ReuseSocket = false;
  80. CurrentAddress = 0;
  81. AcceptedSocket = null;
  82. Total = 0;
  83. error = 0;
  84. EndCalled = 0;
  85. }
  86. public SocketAsyncResult (Socket socket, AsyncCallback callback, object state, SocketOperation operation)
  87. : base (callback, state)
  88. {
  89. this.socket = socket;
  90. this.operation = operation;
  91. }
  92. public SocketError ErrorCode {
  93. get {
  94. SocketException ex = DelayedException as SocketException;
  95. if (ex != null)
  96. return ex.SocketErrorCode;
  97. if (error != 0)
  98. return (SocketError) error;
  99. return SocketError.Success;
  100. }
  101. }
  102. public void CheckIfThrowDelayedException ()
  103. {
  104. if (DelayedException != null) {
  105. socket.is_connected = false;
  106. throw DelayedException;
  107. }
  108. if (error != 0) {
  109. socket.is_connected = false;
  110. throw new SocketException (error);
  111. }
  112. }
  113. internal override void CompleteDisposed ()
  114. {
  115. Complete ();
  116. }
  117. public void Complete ()
  118. {
  119. if (operation != SocketOperation.Receive && socket.is_disposed)
  120. DelayedException = new ObjectDisposedException (socket.GetType ().ToString ());
  121. IsCompleted = true;
  122. AsyncCallback callback = AsyncCallback;
  123. if (callback != null) {
  124. ThreadPool.UnsafeQueueUserWorkItem (_ => callback (this), null);
  125. }
  126. Queue<KeyValuePair<IntPtr, IOSelectorJob>> queue = null;
  127. switch (operation) {
  128. case SocketOperation.Receive:
  129. case SocketOperation.ReceiveFrom:
  130. case SocketOperation.ReceiveGeneric:
  131. case SocketOperation.Accept:
  132. queue = socket.readQ;
  133. break;
  134. case SocketOperation.Send:
  135. case SocketOperation.SendTo:
  136. case SocketOperation.SendGeneric:
  137. queue = socket.writeQ;
  138. break;
  139. }
  140. if (queue != null) {
  141. lock (queue) {
  142. /* queue.Count will only be 0 if the socket is closed while receive/send/accept
  143. * operation(s) are pending and at least one call to this method is waiting
  144. * on the lock while another one calls CompleteAllOnDispose() */
  145. if (queue.Count > 0)
  146. queue.Dequeue (); /* remove ourselves */
  147. if (queue.Count > 0) {
  148. if (!socket.is_disposed) {
  149. IOSelector.Add (queue.Peek ().Key, queue.Peek ().Value);
  150. } else {
  151. /* CompleteAllOnDispose */
  152. KeyValuePair<IntPtr, IOSelectorJob> [] jobs = queue.ToArray ();
  153. for (int i = 0; i < jobs.Length; i++)
  154. ThreadPool.QueueUserWorkItem (j => ((IOSelectorJob) j).MarkDisposed (), jobs [i].Value);
  155. queue.Clear ();
  156. }
  157. }
  158. }
  159. }
  160. // IMPORTANT: 'callback', if any is scheduled from unmanaged code
  161. }
  162. public void Complete (bool synch)
  163. {
  164. CompletedSynchronously = synch;
  165. Complete ();
  166. }
  167. public void Complete (int total)
  168. {
  169. Total = total;
  170. Complete ();
  171. }
  172. public void Complete (Exception e, bool synch)
  173. {
  174. DelayedException = e;
  175. CompletedSynchronously = synch;
  176. Complete ();
  177. }
  178. public void Complete (Exception e)
  179. {
  180. DelayedException = e;
  181. Complete ();
  182. }
  183. public void Complete (Socket s)
  184. {
  185. AcceptedSocket = s;
  186. Complete ();
  187. }
  188. public void Complete (Socket s, int total)
  189. {
  190. AcceptedSocket = s;
  191. Total = total;
  192. Complete ();
  193. }
  194. }
  195. }