2 // System.Net.Sockets.SafeSocketHandle
5 // Marcos Henrich <marcos.henrich@xamarin.com>
10 using System.Threading;
11 using System.Collections.Generic;
12 using Microsoft.Win32.SafeHandles;
14 namespace System.Net.Sockets {
16 sealed class SafeSocketHandle : SafeHandleZeroOrMinusOneIsInvalid {
18 List<Thread> blocking_threads;
20 const int SOCKET_CLOSED = 10004;
22 const int ABORT_RETRIES = 10;
23 static bool THROW_ON_ABORT_RETRIES = Environment.GetEnvironmentVariable("MONO_TESTS_IN_PROGRESS") == "yes";
25 public SafeSocketHandle (IntPtr preexistingHandle, bool ownsHandle) : base (ownsHandle)
27 SetHandle (preexistingHandle);
30 // This is just for marshalling
31 internal SafeSocketHandle () : base (true)
35 protected override bool ReleaseHandle ()
39 Socket.Blocking_internal (handle, false, out error);
41 if (blocking_threads != null) {
42 int abort_attempts = 0;
43 while (blocking_threads.Count > 0) {
44 if (abort_attempts++ >= ABORT_RETRIES) {
45 if (THROW_ON_ABORT_RETRIES)
46 throw new Exception ("Could not abort registered blocking threads before closing socket.");
48 // Attempts to close the socket safely failed.
49 // We give up, and close the socket with pending blocking system calls.
50 // This should not occur, nonetheless if it does this avoids an endless loop.
55 * This method can be called by the DangerousRelease inside RegisterForBlockingSyscall
56 * When this happens blocking_threads contains the current thread.
57 * We can safely close the socket and throw SocketException in RegisterForBlockingSyscall
58 * before the blocking system call.
60 lock (blocking_threads) {
61 if (blocking_threads.Count == 1 && blocking_threads[0] == Thread.CurrentThread)
65 AbortRegisteredThreads ();
66 // Sleep so other threads can resume
71 Socket.Close_internal (handle, out error);
76 public void RegisterForBlockingSyscall ()
78 if (blocking_threads == null)
79 Interlocked.CompareExchange (ref blocking_threads, new List<Thread> (), null);
83 DangerousAddRef (ref release);
85 /* We must use a finally block here to make this atomic. */
86 lock (blocking_threads) {
87 blocking_threads.Add (Thread.CurrentThread);
92 // Handle can be closed by DangerousRelease
94 throw new SocketException (SOCKET_CLOSED);
98 /* This must be called from a finally block! */
99 public void UnRegisterForBlockingSyscall ()
101 //If this NRE, we're in deep problems because Register Must have
102 lock (blocking_threads) {
103 blocking_threads.Remove (Thread.CurrentThread);
107 void AbortRegisteredThreads () {
108 if (blocking_threads == null)
111 lock (blocking_threads) {
112 foreach (var t in blocking_threads)
113 Socket.cancel_blocking_socket_operation (t);