mscorlib(4.0.0.0) API with additions
GC.cs
5 using System.Security;
6 
7 namespace System
8 {
10  [__DynamicallyInvokable]
11  public static class GC
12  {
13  private enum StartNoGCRegionStatus
14  {
15  Succeeded,
16  NotEnoughMemory,
17  AmountTooLarge,
18  AlreadyInProgress
19  }
20 
21  private enum EndNoGCRegionStatus
22  {
23  Succeeded,
24  NotInProgress,
25  GCInduced,
26  AllocationExceeded
27  }
28 
31  [__DynamicallyInvokable]
32  public static int MaxGeneration
33  {
34  [SecuritySafeCritical]
35  [__DynamicallyInvokable]
36  get
37  {
38  return GetMaxGeneration();
39  }
40  }
41 
42  [MethodImpl(MethodImplOptions.InternalCall)]
43  [SecurityCritical]
44  internal static extern int GetGCLatencyMode();
45 
46  [MethodImpl(MethodImplOptions.InternalCall)]
47  [SecurityCritical]
48  internal static extern int SetGCLatencyMode(int newLatencyMode);
49 
50  [DllImport("QCall", CharSet = CharSet.Unicode)]
51  [SecurityCritical]
52  [SuppressUnmanagedCodeSecurity]
53  internal static extern int _StartNoGCRegion(long totalSize, bool lohSizeKnown, long lohSize, bool disallowFullBlockingGC);
54 
55  [DllImport("QCall", CharSet = CharSet.Unicode)]
56  [SecurityCritical]
57  [SuppressUnmanagedCodeSecurity]
58  internal static extern int _EndNoGCRegion();
59 
60  [MethodImpl(MethodImplOptions.InternalCall)]
61  [SecurityCritical]
62  internal static extern int GetLOHCompactionMode();
63 
64  [MethodImpl(MethodImplOptions.InternalCall)]
65  [SecurityCritical]
66  internal static extern void SetLOHCompactionMode(int newLOHCompactionyMode);
67 
68  [MethodImpl(MethodImplOptions.InternalCall)]
69  [SecurityCritical]
70  private static extern int GetGenerationWR(IntPtr handle);
71 
72  [DllImport("QCall", CharSet = CharSet.Unicode)]
73  [SecurityCritical]
74  [SuppressUnmanagedCodeSecurity]
75  private static extern long GetTotalMemory();
76 
77  [DllImport("QCall", CharSet = CharSet.Unicode)]
78  [SecurityCritical]
79  [SuppressUnmanagedCodeSecurity]
80  private static extern void _Collect(int generation, int mode);
81 
82  [MethodImpl(MethodImplOptions.InternalCall)]
83  [SecurityCritical]
84  private static extern int GetMaxGeneration();
85 
86  [MethodImpl(MethodImplOptions.InternalCall)]
87  [SecurityCritical]
88  [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
89  private static extern int _CollectionCount(int generation, int getSpecialGCCount);
90 
91  [MethodImpl(MethodImplOptions.InternalCall)]
92  [SecurityCritical]
93  internal static extern bool IsServerGC();
94 
95  [DllImport("QCall", CharSet = CharSet.Unicode)]
96  [SecurityCritical]
97  [SuppressUnmanagedCodeSecurity]
98  private static extern void _AddMemoryPressure(ulong bytesAllocated);
99 
100  [DllImport("QCall", CharSet = CharSet.Unicode)]
101  [SecurityCritical]
102  [SuppressUnmanagedCodeSecurity]
103  private static extern void _RemoveMemoryPressure(ulong bytesAllocated);
104 
109  [SecurityCritical]
110  [__DynamicallyInvokable]
111  public static void AddMemoryPressure(long bytesAllocated)
112  {
113  if (bytesAllocated <= 0)
114  {
115  throw new ArgumentOutOfRangeException("bytesAllocated", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
116  }
117  if (4 == IntPtr.Size && bytesAllocated > int.MaxValue)
118  {
119  throw new ArgumentOutOfRangeException("pressure", Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegInt32"));
120  }
121  _AddMemoryPressure((ulong)bytesAllocated);
122  }
123 
128  [SecurityCritical]
129  [__DynamicallyInvokable]
130  public static void RemoveMemoryPressure(long bytesAllocated)
131  {
132  if (bytesAllocated <= 0)
133  {
134  throw new ArgumentOutOfRangeException("bytesAllocated", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
135  }
136  if (4 == IntPtr.Size && bytesAllocated > int.MaxValue)
137  {
138  throw new ArgumentOutOfRangeException("bytesAllocated", Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegInt32"));
139  }
140  _RemoveMemoryPressure((ulong)bytesAllocated);
141  }
142 
146  [MethodImpl(MethodImplOptions.InternalCall)]
147  [SecuritySafeCritical]
148  public static extern int GetGeneration(object obj);
149 
154  [__DynamicallyInvokable]
155  public static void Collect(int generation)
156  {
157  Collect(generation, GCCollectionMode.Default);
158  }
159 
161  [SecuritySafeCritical]
162  [__DynamicallyInvokable]
163  public static void Collect()
164  {
165  _Collect(-1, 2);
166  }
167 
174  [SecuritySafeCritical]
175  [__DynamicallyInvokable]
176  public static void Collect(int generation, GCCollectionMode mode)
177  {
178  Collect(generation, mode, blocking: true);
179  }
180 
189  [SecuritySafeCritical]
190  [__DynamicallyInvokable]
191  public static void Collect(int generation, GCCollectionMode mode, bool blocking)
192  {
193  Collect(generation, mode, blocking, compacting: false);
194  }
195 
203  [SecuritySafeCritical]
204  public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting)
205  {
206  if (generation < 0)
207  {
208  throw new ArgumentOutOfRangeException("generation", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
209  }
210  if (mode < GCCollectionMode.Default || mode > GCCollectionMode.Optimized)
211  {
212  throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_Enum"));
213  }
214  int num = 0;
215  if (mode == GCCollectionMode.Optimized)
216  {
217  num |= 4;
218  }
219  if (compacting)
220  {
221  num |= 8;
222  }
223  if (blocking)
224  {
225  num |= 2;
226  }
227  else if (!compacting)
228  {
229  num |= 1;
230  }
231  _Collect(generation, num);
232  }
233 
239  [SecuritySafeCritical]
240  [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
241  [__DynamicallyInvokable]
242  public static int CollectionCount(int generation)
243  {
244  if (generation < 0)
245  {
246  throw new ArgumentOutOfRangeException("generation", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
247  }
248  return _CollectionCount(generation, 0);
249  }
250 
251  [SecuritySafeCritical]
252  [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
253  internal static int CollectionCount(int generation, bool getSpecialGCCount)
254  {
255  if (generation < 0)
256  {
257  throw new ArgumentOutOfRangeException("generation", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
258  }
259  return _CollectionCount(generation, getSpecialGCCount ? 1 : 0);
260  }
261 
264  [MethodImpl(MethodImplOptions.NoInlining)]
265  [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
266  [__DynamicallyInvokable]
267  public static void KeepAlive(object obj)
268  {
269  }
270 
275  [SecuritySafeCritical]
276  public static int GetGeneration(WeakReference wo)
277  {
278  int generationWR = GetGenerationWR(wo.m_handle);
279  KeepAlive(wo);
280  return generationWR;
281  }
282 
283  [DllImport("QCall", CharSet = CharSet.Unicode)]
284  [SecurityCritical]
285  [SuppressUnmanagedCodeSecurity]
286  private static extern void _WaitForPendingFinalizers();
287 
289  [SecuritySafeCritical]
290  [__DynamicallyInvokable]
291  public static void WaitForPendingFinalizers()
292  {
293  _WaitForPendingFinalizers();
294  }
295 
296  [MethodImpl(MethodImplOptions.InternalCall)]
297  [SecurityCritical]
298  [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
299  private static extern void _SuppressFinalize(object o);
300 
305  [SecuritySafeCritical]
306  [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
307  [__DynamicallyInvokable]
308  public static void SuppressFinalize(object obj)
309  {
310  if (obj == null)
311  {
312  throw new ArgumentNullException("obj");
313  }
314  _SuppressFinalize(obj);
315  }
316 
317  [MethodImpl(MethodImplOptions.InternalCall)]
318  [SecurityCritical]
319  private static extern void _ReRegisterForFinalize(object o);
320 
325  [SecuritySafeCritical]
326  [__DynamicallyInvokable]
327  public static void ReRegisterForFinalize(object obj)
328  {
329  if (obj == null)
330  {
331  throw new ArgumentNullException("obj");
332  }
333  _ReRegisterForFinalize(obj);
334  }
335 
340  [SecuritySafeCritical]
341  [__DynamicallyInvokable]
342  public static long GetTotalMemory(bool forceFullCollection)
343  {
344  long totalMemory = GetTotalMemory();
345  if (!forceFullCollection)
346  {
347  return totalMemory;
348  }
349  int num = 20;
350  long num2 = totalMemory;
351  float num3;
352  do
353  {
355  Collect();
356  totalMemory = num2;
357  num2 = GetTotalMemory();
358  num3 = (float)(num2 - totalMemory) / (float)totalMemory;
359  }
360  while (num-- > 0 && (!(-0.05 < (double)num3) || !((double)num3 < 0.05)));
361  return num2;
362  }
363 
364  [MethodImpl(MethodImplOptions.InternalCall)]
365  [SecurityCritical]
366  private static extern bool _RegisterForFullGCNotification(int maxGenerationPercentage, int largeObjectHeapPercentage);
367 
368  [MethodImpl(MethodImplOptions.InternalCall)]
369  private static extern bool _CancelFullGCNotification();
370 
371  [MethodImpl(MethodImplOptions.InternalCall)]
372  private static extern int _WaitForFullGCApproach(int millisecondsTimeout);
373 
374  [MethodImpl(MethodImplOptions.InternalCall)]
375  private static extern int _WaitForFullGCComplete(int millisecondsTimeout);
376 
382  [SecurityCritical]
383  public static void RegisterForFullGCNotification(int maxGenerationThreshold, int largeObjectHeapThreshold)
384  {
385  if (maxGenerationThreshold <= 0 || maxGenerationThreshold >= 100)
386  {
387  throw new ArgumentOutOfRangeException("maxGenerationThreshold", string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"), 1, 99));
388  }
389  if (largeObjectHeapThreshold <= 0 || largeObjectHeapThreshold >= 100)
390  {
391  throw new ArgumentOutOfRangeException("largeObjectHeapThreshold", string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"), 1, 99));
392  }
393  if (!_RegisterForFullGCNotification(maxGenerationThreshold, largeObjectHeapThreshold))
394  {
395  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotWithConcurrentGC"));
396  }
397  }
398 
401  [SecurityCritical]
402  public static void CancelFullGCNotification()
403  {
404  if (!_CancelFullGCNotification())
405  {
406  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotWithConcurrentGC"));
407  }
408  }
409 
412  [SecurityCritical]
414  {
415  return (GCNotificationStatus)_WaitForFullGCApproach(-1);
416  }
417 
423  [SecurityCritical]
424  public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout)
425  {
426  if (millisecondsTimeout < -1)
427  {
428  throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
429  }
430  return (GCNotificationStatus)_WaitForFullGCApproach(millisecondsTimeout);
431  }
432 
435  [SecurityCritical]
437  {
438  return (GCNotificationStatus)_WaitForFullGCComplete(-1);
439  }
440 
446  [SecurityCritical]
447  public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout)
448  {
449  if (millisecondsTimeout < -1)
450  {
451  throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
452  }
453  return (GCNotificationStatus)_WaitForFullGCComplete(millisecondsTimeout);
454  }
455 
456  [SecurityCritical]
457  private static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC)
458  {
459  switch (_StartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC))
460  {
461  case 2:
462  throw new ArgumentOutOfRangeException("totalSize", "totalSize is too large. For more information about setting the maximum size, see \"Latency Modes\" in http://go.microsoft.com/fwlink/?LinkId=522706");
463  case 3:
464  throw new InvalidOperationException("The NoGCRegion mode was already in progress");
465  case 1:
466  return false;
467  default:
468  return true;
469  }
470  }
471 
479  [SecurityCritical]
480  public static bool TryStartNoGCRegion(long totalSize)
481  {
482  return StartNoGCRegionWorker(totalSize, hasLohSize: false, 0L, disallowFullBlockingGC: false);
483  }
484 
493  [SecurityCritical]
494  public static bool TryStartNoGCRegion(long totalSize, long lohSize)
495  {
496  return StartNoGCRegionWorker(totalSize, hasLohSize: true, lohSize, disallowFullBlockingGC: false);
497  }
498 
508  [SecurityCritical]
509  public static bool TryStartNoGCRegion(long totalSize, bool disallowFullBlockingGC)
510  {
511  return StartNoGCRegionWorker(totalSize, hasLohSize: false, 0L, disallowFullBlockingGC);
512  }
513 
524  [SecurityCritical]
525  public static bool TryStartNoGCRegion(long totalSize, long lohSize, bool disallowFullBlockingGC)
526  {
527  return StartNoGCRegionWorker(totalSize, hasLohSize: true, lohSize, disallowFullBlockingGC);
528  }
529 
530  [SecurityCritical]
531  private static EndNoGCRegionStatus EndNoGCRegionWorker()
532  {
533  switch (_EndNoGCRegion())
534  {
535  case 1:
536  throw new InvalidOperationException("NoGCRegion mode must be set");
537  case 2:
538  throw new InvalidOperationException("Garbage collection was induced in NoGCRegion mode");
539  case 3:
540  throw new InvalidOperationException("Allocated memory exceeds specified memory for NoGCRegion mode");
541  default:
542  return EndNoGCRegionStatus.Succeeded;
543  }
544  }
545 
548  [SecurityCritical]
549  public static void EndNoGCRegion()
550  {
551  EndNoGCRegionWorker();
552  }
553  }
554 }
GCCollectionMode
Specifies the behavior for a forced garbage collection.
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
static void EndNoGCRegion()
Ends the no GC region latency mode.
Definition: GC.cs:549
static void SuppressFinalize(object obj)
Requests that the common language runtime not call the finalizer for the specified object.
Definition: GC.cs:308
static long GetTotalMemory(bool forceFullCollection)
Retrieves the number of bytes currently thought to be allocated. A parameter indicates whether this m...
Definition: GC.cs:342
static GCNotificationStatus WaitForFullGCApproach()
Returns the status of a registered notification for determining whether a full, blocking garbage coll...
Definition: GC.cs:413
static void ReRegisterForFinalize(object obj)
Requests that the system call the finalizer for the specified object for which M:System....
Definition: GC.cs:327
static void Collect(int generation)
Forces an immediate garbage collection from generation 0 through a specified generation.
Definition: GC.cs:155
static void Collect(int generation, GCCollectionMode mode, bool blocking)
Forces a garbage collection from generation 0 through a specified generation, at a time specified by ...
Definition: GC.cs:191
Definition: __Canon.cs:3
The exception that is thrown when the value of an argument is outside the allowable range of values a...
static int GetGeneration(object obj)
Returns the current generation number of the specified object.
static void KeepAlive(object obj)
References the specified object, which makes it ineligible for garbage collection from the start of t...
Definition: GC.cs:267
static bool TryStartNoGCRegion(long totalSize, long lohSize)
Attempts to disallow garbage collection during the execution of a critical path if a specified amount...
Definition: GC.cs:494
Cer
Specifies a method's behavior when called within a constrained execution region.
Definition: Cer.cs:5
Represents a weak reference, which references an object while still allowing that object to be reclai...
static void RegisterForFullGCNotification(int maxGenerationThreshold, int largeObjectHeapThreshold)
Specifies that a garbage collection notification should be raised when conditions favor full garbage ...
Definition: GC.cs:383
Provides information about, and means to manipulate, the current environment and platform....
Definition: Environment.cs:21
static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout)
Returns, in a specified time-out period, the status of a registered notification for determining whet...
Definition: GC.cs:447
static void CancelFullGCNotification()
Cancels the registration of a garbage collection notification.
Definition: GC.cs:402
static void Collect(int generation, GCCollectionMode mode)
Forces a garbage collection from generation 0 through a specified generation, at a time specified by ...
Definition: GC.cs:176
static GCNotificationStatus WaitForFullGCComplete()
Returns the status of a registered notification for determining whether a full, blocking garbage coll...
Definition: GC.cs:436
static bool TryStartNoGCRegion(long totalSize, bool disallowFullBlockingGC)
Attempts to disallow garbage collection during the execution of a critical path if a specified amount...
Definition: GC.cs:509
A platform-specific type that is used to represent a pointer or a handle.
Definition: IntPtr.cs:14
static int GetGeneration(WeakReference wo)
Returns the current generation number of the target of a specified weak reference.
Definition: GC.cs:276
static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout)
Returns, in a specified time-out period, the status of a registered notification for determining whet...
Definition: GC.cs:424
static void Collect()
Forces an immediate garbage collection of all generations.
Definition: GC.cs:163
MethodImplOptions
Defines the details of how a method is implemented.
CharSet
Dictates which character set marshaled strings should use.
Definition: CharSet.cs:7
GCNotificationStatus
Provides information about the current registration for notification of the next full garbage collect...
Controls the system garbage collector, a service that automatically reclaims unused memory.
Definition: GC.cs:11
static CultureInfo CurrentCulture
Gets or sets the T:System.Globalization.CultureInfo object that represents the culture used by the cu...
Definition: CultureInfo.cs:120
static int Size
Gets the size of this instance.
Definition: IntPtr.cs:27
The notification was successful and the registration was not canceled.
static int MaxGeneration
Gets the maximum number of generations that the system currently supports.
Definition: GC.cs:33
static int CollectionCount(int generation)
Returns the number of times garbage collection has occurred for the specified generation of objects.
Definition: GC.cs:242
The exception that is thrown when a method call is invalid for the object's current state.
Consistency
Specifies a reliability contract.
Definition: Consistency.cs:5
static bool TryStartNoGCRegion(long totalSize, long lohSize, bool disallowFullBlockingGC)
Attempts to disallow garbage collection during the execution of a critical path if a specified amount...
Definition: GC.cs:525
static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting)
Forces a garbage collection from generation 0 through a specified generation, at a time specified by ...
Definition: GC.cs:204
Provides information about a specific culture (called a locale for unmanaged code development)....
Definition: CultureInfo.cs:16
static void AddMemoryPressure(long bytesAllocated)
Informs the runtime of a large allocation of unmanaged memory that should be taken into account when ...
Definition: GC.cs:111
static bool TryStartNoGCRegion(long totalSize)
Attempts to disallow garbage collection during the execution of a critical path if a specified amount...
Definition: GC.cs:480
static void WaitForPendingFinalizers()
Suspends the current thread until the thread that is processing the queue of finalizers has emptied t...
Definition: GC.cs:291
static void RemoveMemoryPressure(long bytesAllocated)
Informs the runtime that unmanaged memory has been released and no longer needs to be taken into acco...
Definition: GC.cs:130