Creating an instance of the MemoryFailPoint class creates a memory gate. A memory gate checks for sufficient resources before initiating an activity that requires a large amount of memory. Failing the check results in an InsufficientMemoryException exception being thrown. This exception prevents an operation from being started and reduces the possibility of failure due to lack of resources. This enables you decrease performance to avoid an OutOfMemoryException exception and any state corruption that may result from improper handling of the exception in arbitrary locations in your code.

Important

This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the “Using an Object that Implements IDisposable” section in the IDisposable interface topic.

By throwing an InsufficientMemoryException exception, an application can distinguish between an estimate that an operation will not be able to complete and a partially completed operation that may have corrupted the application state. This allows an application to reduce the frequency of a pessimistic escalation policy, which may require unloading the current AppDomain or recycling the process.

MemoryFailPoint checks to see whether sufficient memory and consecutive virtual address space are available in all garbage collection heaps, and may increase the size of the swap file. MemoryFailPoint makes no guarantees regarding the long-term availability of the memory during the lifetime of the gate, but callers should always use the Dispose method to ensure that resources associated with MemoryFailPoint are released.

To use a memory gate, you must create a MemoryFailPoint object and specify the number of megabytes (MB) of memory that the next operation is expected to use. If enough memory is not available, an InsufficientMemoryException exception is thrown.

MemoryFailPoint enables an application to slow itself to avoid running out of memory in a corrupting manner. It should be used within a lexical scope. The following example launches threads to process items in a work queue. Before each thread is launched, the available memory resources are checked using MemoryFailPoint. If an exception is thrown, the main method waits until memory is available before launching the next thread.