Merge pull request #1695 from gregoryyoung/master
[mono.git] / mcs / class / corlib / System.Threading / ThreadPool.cs
1 //
2 // System.Threading.ThreadPool.cs
3 //
4 // Author:
5 //   Patrik Torstensson
6 //   Dick Porter (dick@ximian.com)
7 //   Maurer Dietmar (dietmar@ximian.com)
8 //
9 // (C) Ximian, Inc.  http://www.ximian.com
10 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System.Collections;
33 using System.Collections.Generic;
34 using System.Globalization;
35 using System.Runtime.CompilerServices;
36 using System.Runtime.Remoting.Messaging;
37 using System.Runtime.InteropServices;
38 using System.Security;
39 using System.Security.Permissions;
40
41 namespace System.Threading {
42
43         public static class ThreadPool {
44
45                 [Obsolete("This method is obsolete, use BindHandle(SafeHandle) instead")]
46                 public static bool BindHandle (IntPtr osHandle)
47                 {
48                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
49                                 return Microsoft.ThreadPool.BindHandle (osHandle);
50                         else
51                                 return true;
52                 }
53
54                 public static bool BindHandle (SafeHandle osHandle)
55                 {
56                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool) {
57                                 return Microsoft.ThreadPool.BindHandle (osHandle);
58                         } else {
59                                 if (osHandle == null)
60                                         throw new ArgumentNullException ("osHandle");
61                         
62                                 return true;
63                         }
64                 }
65
66                 public static void GetAvailableThreads (out int workerThreads, out int completionPortThreads)
67                 {
68                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
69                                 Microsoft.ThreadPool.GetAvailableThreads (out workerThreads, out completionPortThreads);
70                         else
71                                 GetAvailableThreads_internal (out workerThreads, out completionPortThreads);
72                 }
73
74                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
75                 static extern void GetAvailableThreads_internal (out int workerThreads, out int completionPortThreads);
76
77                 public static void GetMaxThreads (out int workerThreads, out int completionPortThreads)
78                 {
79                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
80                                 Microsoft.ThreadPool.GetMaxThreads (out workerThreads, out completionPortThreads);
81                         else
82                                 GetMaxThreads_internal (out workerThreads, out completionPortThreads);
83                 }
84
85                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
86                 static extern void GetMaxThreads_internal (out int workerThreads, out int completionPortThreads);
87
88                 public static void GetMinThreads (out int workerThreads, out int completionPortThreads)
89                 {
90                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
91                                 Microsoft.ThreadPool.GetMinThreads (out workerThreads, out completionPortThreads);
92                         else
93                                 GetMinThreads_internal (out workerThreads, out completionPortThreads);
94                 }
95
96                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
97                 static extern void GetMinThreads_internal (out int workerThreads, out int completionPortThreads);
98
99                 [MonoTODO("The min number of completion port threads is not evaluated.")]
100                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
101                 public static bool SetMinThreads (int workerThreads, int completionPortThreads)
102                 {
103                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
104                                 return Microsoft.ThreadPool.SetMinThreads (workerThreads, completionPortThreads);
105                         else
106                                 return SetMinThreads_internal (workerThreads, completionPortThreads);
107                 }
108
109                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
110                 static extern bool SetMinThreads_internal (int workerThreads, int completionPortThreads);
111
112                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
113                 public static bool SetMaxThreads (int workerThreads, int completionPortThreads)
114                 {
115                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
116                                 return Microsoft.ThreadPool.SetMaxThreads (workerThreads, completionPortThreads);
117                         else
118                                 return SetMaxThreads_internal (workerThreads, completionPortThreads);
119                 }
120
121                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
122                 static extern bool SetMaxThreads_internal (int workerThreads, int completionPortThreads);
123
124                 public static bool QueueUserWorkItem (WaitCallback callBack)
125                 {
126                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
127                                 return Microsoft.ThreadPool.QueueUserWorkItem (callBack, null);
128                         else
129                                 return QueueUserWorkItem (callBack, null);
130                 }
131
132                 public static bool QueueUserWorkItem (WaitCallback callBack, object state)
133                 {
134                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool) {
135                                 return Microsoft.ThreadPool.QueueUserWorkItem (callBack, state);
136                         } else {
137                                 if (callBack == null)
138                                         throw new ArgumentNullException ("callBack");
139
140                                 if (callBack.IsTransparentProxy ()) {
141                                         IAsyncResult ar = callBack.BeginInvoke (state, null, null);
142                                         if (ar == null)
143                                                 return false;
144                                 } else {
145                                         AsyncResult ares = new AsyncResult (callBack, state, true);
146                                         pool_queue (ares);
147                                 }
148                                 return true;
149                         }
150                 }
151
152                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
153                 static extern void pool_queue (AsyncResult ares);
154
155                 // TODO: It should be interface interface only to avoid extra allocation
156                 internal static void QueueWorkItem (WaitCallback callBack, object state)
157                 {
158                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
159                                 Microsoft.ThreadPool.QueueUserWorkItem (callBack, state);
160                         else
161                                 pool_queue (new AsyncResult (callBack, state, false));
162                 }
163
164                 public static RegisteredWaitHandle RegisterWaitForSingleObject (WaitHandle waitObject,
165                                                                                 WaitOrTimerCallback callBack,
166                                                                                 object state,
167                                                                                 int millisecondsTimeOutInterval,
168                                                                                 bool executeOnlyOnce)
169                 {
170                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
171                                 return Microsoft.ThreadPool.RegisterWaitForSingleObject (waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce);
172                         else
173                                 return RegisterWaitForSingleObject (waitObject, callBack, state, (long) millisecondsTimeOutInterval, executeOnlyOnce);
174                 }
175
176                 public static RegisteredWaitHandle RegisterWaitForSingleObject (WaitHandle waitObject,
177                                                                                 WaitOrTimerCallback callBack,
178                                                                                 object state,
179                                                                                 long millisecondsTimeOutInterval,
180                                                                                 bool executeOnlyOnce)
181                 {
182                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool) {
183                                 return Microsoft.ThreadPool.RegisterWaitForSingleObject (waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce);
184                         } else {
185                                 if (waitObject == null)
186                                         throw new ArgumentNullException ("waitObject");
187
188                                 if (callBack == null)
189                                         throw new ArgumentNullException ("callBack");
190                         
191                                 if (millisecondsTimeOutInterval < -1)
192                                         throw new ArgumentOutOfRangeException ("timeout", "timeout < -1");
193
194                                 if (millisecondsTimeOutInterval > Int32.MaxValue)
195                                         throw new NotSupportedException ("Timeout is too big. Maximum is Int32.MaxValue");
196
197                                 TimeSpan timeout = new TimeSpan (0, 0, 0, 0, (int) millisecondsTimeOutInterval);
198                         
199                                 RegisteredWaitHandle waiter = new RegisteredWaitHandle (waitObject, callBack, state,
200                                                                                         timeout, executeOnlyOnce);
201                                 QueueUserWorkItem (new WaitCallback (waiter.Wait), null);
202                                 return waiter;
203                         }
204                 }
205
206                 public static RegisteredWaitHandle RegisterWaitForSingleObject (WaitHandle waitObject,
207                                                                                 WaitOrTimerCallback callBack,
208                                                                                 object state,
209                                                                                 TimeSpan timeout,
210                                                                                 bool executeOnlyOnce)
211                 {
212                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
213                                 return Microsoft.ThreadPool.RegisterWaitForSingleObject (waitObject, callBack, state, timeout, executeOnlyOnce);
214                         else
215                                 return RegisterWaitForSingleObject (waitObject, callBack, state, (long) timeout.TotalMilliseconds, executeOnlyOnce);
216
217                 }
218
219                 [CLSCompliant(false)]
220                 public static RegisteredWaitHandle RegisterWaitForSingleObject (WaitHandle waitObject,
221                                                                                 WaitOrTimerCallback callBack,
222                                                                                 object state,
223                                                                                 uint millisecondsTimeOutInterval,
224                                                                                 bool executeOnlyOnce)
225                 {
226                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
227                                 return Microsoft.ThreadPool.RegisterWaitForSingleObject (waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce);
228                         else
229                                 return RegisterWaitForSingleObject (waitObject, callBack, state, (long) millisecondsTimeOutInterval, executeOnlyOnce);
230                 }
231
232                 [CLSCompliant (false)]
233                 unsafe public static bool UnsafeQueueNativeOverlapped (NativeOverlapped *overlapped)
234                 {
235                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
236                                 return Microsoft.ThreadPool.UnsafeQueueNativeOverlapped (overlapped);
237                         else
238                                 throw new NotImplementedException ();
239                 }
240
241 #if !NET_2_1 || MOBILE
242
243                 [SecurityPermission (SecurityAction.Demand, ControlEvidence=true, ControlPolicy=true)]
244                 public static bool UnsafeQueueUserWorkItem (WaitCallback callBack, object state)
245                 {
246                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool) {
247                                 return Microsoft.ThreadPool.UnsafeQueueUserWorkItem (callBack, state);
248                         } else {
249                                 if (callBack == null)
250                                         throw new ArgumentNullException ("callBack");
251
252                                 // no stack propagation here (that's why it's unsafe and requires extra security permissions)
253                                 if (!callBack.IsTransparentProxy ()) {
254                                         AsyncResult ares = new AsyncResult (callBack, state, false);
255                                         pool_queue (ares);
256                                         return true;
257                                 }
258                                 try {
259                                         if (!ExecutionContext.IsFlowSuppressed ())
260                                                 ExecutionContext.SuppressFlow (); // on current thread only
261                                         IAsyncResult ar = callBack.BeginInvoke (state, null, null);
262                                         if (ar == null)
263                                                 return false;
264                                 } finally {
265                                         if (ExecutionContext.IsFlowSuppressed ())
266                                                 ExecutionContext.RestoreFlow ();
267                                 }
268                                 return true;
269                         }
270                 }
271                 
272                 [MonoTODO("Not implemented")]
273                 [SecurityPermission (SecurityAction.Demand, ControlEvidence=true, ControlPolicy=true)]
274                 public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject (WaitHandle waitObject,
275                         WaitOrTimerCallback callBack, object state, int millisecondsTimeOutInterval,
276                         bool executeOnlyOnce) 
277                 {
278                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
279                                 return Microsoft.ThreadPool.UnsafeRegisterWaitForSingleObject (waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce);
280                         else
281                                 throw new NotImplementedException ();
282                 }
283                 
284                 [MonoTODO("Not implemented")]
285                 [SecurityPermission (SecurityAction.Demand, ControlEvidence=true, ControlPolicy=true)]
286                 public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject (WaitHandle waitObject,
287                         WaitOrTimerCallback callBack, object state, long millisecondsTimeOutInterval,
288                         bool executeOnlyOnce) 
289                 {
290                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
291                                 return Microsoft.ThreadPool.UnsafeRegisterWaitForSingleObject (waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce);
292                         else
293                                 throw new NotImplementedException ();
294                 }
295
296                 [MonoTODO("Not implemented")]
297                 [SecurityPermission (SecurityAction.Demand, ControlEvidence=true, ControlPolicy=true)]
298                 public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject (WaitHandle waitObject,
299                         WaitOrTimerCallback callBack, object state, TimeSpan timeout,
300                         bool executeOnlyOnce) 
301                 {
302                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
303                                 return Microsoft.ThreadPool.UnsafeRegisterWaitForSingleObject (waitObject, callBack, state, timeout, executeOnlyOnce);
304                         else
305                                 throw new NotImplementedException ();
306                 }
307
308                 [MonoTODO("Not implemented")]
309                 [CLSCompliant (false)]
310                 [SecurityPermission (SecurityAction.Demand, ControlEvidence=true, ControlPolicy=true)]
311                 public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject (WaitHandle waitObject,
312                         WaitOrTimerCallback callBack, object state, uint millisecondsTimeOutInterval,
313                         bool executeOnlyOnce) 
314                 {
315                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
316                                 return Microsoft.ThreadPool.UnsafeRegisterWaitForSingleObject (waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce);
317                         else
318                                 throw new NotImplementedException ();
319                 }
320
321 #endif
322
323 #region ReferenceSources
324                 // Extracted from ../../../../external/referencesource/mscorlib/system/threading/threadpool.cs
325                 internal static void UnsafeQueueCustomWorkItem(IThreadPoolWorkItem workItem, bool forceGlobal)
326                 {
327                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
328                                 Microsoft.ThreadPool.UnsafeQueueCustomWorkItem (workItem, forceGlobal);
329                         else
330                                 QueueWorkItem ((obj) => ((IThreadPoolWorkItem)obj).ExecuteWorkItem (), workItem);
331                 }
332
333                 internal static IEnumerable<IThreadPoolWorkItem> GetQueuedWorkItems()
334                 {
335                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
336                                 return Microsoft.ThreadPool.GetQueuedWorkItems ();
337                         else
338                                 return new IThreadPoolWorkItem [0];
339                 }
340
341                 internal static bool TryPopCustomWorkItem(IThreadPoolWorkItem workItem)
342                 {
343                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
344                                 return Microsoft.ThreadPool.TryPopCustomWorkItem (workItem);
345                         else
346                                 return false;
347                 }
348
349                 internal static void NotifyWorkItemProgress()
350                 {
351                         if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
352                                 Microsoft.ThreadPool.NotifyWorkItemProgress ();
353                 }
354 #endregion
355         }
356 }