MemoryFailPoint MemoryFailPoint MemoryFailPoint MemoryFailPoint Class

Definición

Comprueba si hay suficientes recursos de memoria antes de ejecutar una operación.Checks for sufficient memory resources before executing an operation. Esta clase no puede heredarse.This class cannot be inherited.

public ref class MemoryFailPoint sealed : System::Runtime::ConstrainedExecution::CriticalFinalizerObject, IDisposable
public sealed class MemoryFailPoint : System.Runtime.ConstrainedExecution.CriticalFinalizerObject, IDisposable
type MemoryFailPoint = class
    inherit CriticalFinalizerObject
    interface IDisposable
Public NotInheritable Class MemoryFailPoint
Inherits CriticalFinalizerObject
Implements IDisposable
Herencia
Implementaciones

Ejemplos

MemoryFailPointpermite que una aplicación se ralentice para evitar quedarse sin memoria de forma dañada.MemoryFailPoint enables an application to slow itself to avoid running out of memory in a corrupting manner. Debe usarse dentro de un ámbito léxico.It should be used within a lexical scope. En el ejemplo siguiente se inician subprocesos para procesar elementos en una cola de trabajo.The following example launches threads to process items in a work queue. Antes de que se inicie cada subproceso, se comprueban MemoryFailPointlos recursos de memoria disponibles mediante.Before each thread is launched, the available memory resources are checked using MemoryFailPoint. Si se produce una excepción, el método Main espera hasta que haya memoria disponible antes de iniciar el siguiente subproceso.If an exception is thrown, the main method waits until memory is available before launching the next thread.

using System;
using System.Runtime;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Collections;

class MemoryFailPointExample
{
    // Allocate in chunks of 64 megabytes.
    private const uint chunkSize = 64 << 20;
    // Use more than the total user-available address space (on 32 bit machines)
    // to drive towards getting an InsufficientMemoryException.
    private const uint numWorkItems = 1 + ((1U << 31) / chunkSize);
    static Queue workQueue = new Queue(50);

    // This value can be computed separately and hard-coded into the application.
    // The method is included to illustrate the technique.
    private static int EstimateMemoryUsageInMB()
    {
        int memUsageInMB = 0;

        long memBefore = GC.GetTotalMemory(true);
        int numGen0Collections = GC.CollectionCount(0);
        // Execute a test version of the method to estimate memory requirements.
        // This test method only exists to determine the memory requirements.
        ThreadMethod();
        // Includes garbage generated by the worker function.
        long memAfter = GC.GetTotalMemory(false);
        // If a garbage collection occurs during the measuring, you might need a greater memory requirement.
        Console.WriteLine("Did a GC occur while measuring?  {0}", numGen0Collections == GC.CollectionCount(0));
        // Set the field used as the parameter for the MemoryFailPoint constructor.
        long memUsage = (memAfter - memBefore);
        if (memUsage < 0)
        {
            Console.WriteLine("GC's occurred while measuring memory usage.  Try measuring again.");
            memUsage = 1 << 20;
        }

        // Round up to the nearest MB.
        memUsageInMB = (int)(1 + (memUsage >> 20));
        Console.WriteLine("Memory usage estimate: {0} bytes, rounded to {1} MB", memUsage, memUsageInMB);
        return memUsageInMB;
    }

    static void Main()
    {
        Console.WriteLine("Attempts to allocate more than 2 GB of memory across worker threads.");
        int memUsageInMB = EstimateMemoryUsageInMB();

        // For a production application consider using the threadpool instead.
        Thread[] threads = new Thread[numWorkItems];
        // Create a work queue to be processed by multiple threads.
        int n = 0;
        for (n = 0; n < numWorkItems; n++)
            workQueue.Enqueue(n);
        // Continue to launch threads until the work queue is empty.
        while (workQueue.Count > 0)
        {
            Console.WriteLine(" GC heap (live + garbage): {0} MB", GC.GetTotalMemory(false) >> 20);
            MemoryFailPoint memFailPoint = null;
            try
            {
                // Check for available memory.
                memFailPoint = new MemoryFailPoint(memUsageInMB);
                n = (int)workQueue.Dequeue();
                threads[n] =
                    new Thread(new ParameterizedThreadStart(ThreadMethod));
                WorkerState state = new WorkerState(n, memFailPoint);
                threads[n].Start(state);
                Thread.Sleep(10);
            }
            catch (InsufficientMemoryException e)
            {
                // MemoryFailPoint threw an exception, handle by sleeping for a while,  then 
                // continue processing the queue.
                Console.WriteLine("Expected InsufficientMemoryException thrown.  Message: " + e.Message);
                // We could optionally sleep until a running worker thread 
                // has finished, like this:  threads[joinCount++].Join();
                Thread.Sleep(1000);
            }
        }

        Console.WriteLine("WorkQueue is empty - blocking to ensure all threads quit (each thread sleeps for 10 seconds)");
        foreach (Thread t in threads)
            t.Join();
        Console.WriteLine("All worker threads are finished - exiting application.");
    }

    // Test version of the working code to determine memory requirements.
    static void ThreadMethod()
    {
        byte[] bytes = new byte[chunkSize];
    }

    internal class WorkerState
    {
        internal int _threadNumber;
        internal MemoryFailPoint _memFailPoint;

        internal WorkerState(int threadNumber, MemoryFailPoint memoryFailPoint)
        {
            _threadNumber = threadNumber;
            _memFailPoint = memoryFailPoint;
        }

        internal int ThreadNumber
        {
            get { return _threadNumber; }
        }

        internal MemoryFailPoint MemoryFailPoint
        {
            get { return _memFailPoint; }
        }
    }

    // The method that does the work.
    static void ThreadMethod(Object o)
    {
        WorkerState state = (WorkerState)o;
        Console.WriteLine("Executing ThreadMethod, " +
            "thread number {0}.", state.ThreadNumber);
        byte[] bytes = null;
        try
        {
            bytes = new byte[chunkSize];
            // Allocated all the memory needed for this workitem.
            // Now dispose of the MemoryFailPoint, then process the workitem.
            state.MemoryFailPoint.Dispose();
        }
        catch (OutOfMemoryException oom)
        {
            Console.Beep();
            Console.WriteLine("Unexpected OutOfMemory exception thrown: " + oom);
        }

        // Do work here, possibly taking a lock if this app needs 
        // synchronization between worker threads and/or the main thread.

        // Keep the thread alive for awhile to simulate a running thread.
        Thread.Sleep(10000);

        // A real thread would use the byte[], but to be an illustrative sample,
        // explicitly keep the byte[] alive to help exhaust the memory.
        GC.KeepAlive(bytes);
        Console.WriteLine("Thread {0} is finished.", state.ThreadNumber);

    }
}

Comentarios

Nota

Esta clase está pensada para su uso en el desarrollo avanzado.This class is intended for use in advanced development.

Al crear una instancia de MemoryFailPoint la clase, se crea una puerta de memoria.Creating an instance of the MemoryFailPoint class creates a memory gate. Una puerta de memoria comprueba los recursos necesarios antes de iniciar una actividad que requiere una gran cantidad de memoria.A memory gate checks for sufficient resources before initiating an activity that requires a large amount of memory. Si se produce un error en la InsufficientMemoryException comprobación, se produce una excepción.Failing the check results in an InsufficientMemoryException exception being thrown. Esta excepción evita que se inicie una operación y reduce la posibilidad de que se produzca un error debido a la falta de recursos.This exception prevents an operation from being started and reduces the possibility of failure due to lack of resources. Esto le permite reducir el rendimiento para evitar OutOfMemoryException una excepción y cualquier daño de estado que pueda ser el resultado de un control inadecuado de la excepción en ubicaciones arbitrarias en el código.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.

Importante

Este tipo implementa la interfaz IDisposable.This type implements the IDisposable interface. Cuando haya terminado de utilizar el tipo, debe desecharlo directa o indirectamente.When you have finished using the type, you should dispose of it either directly or indirectly. Para eliminar el tipo directamente, llame a su método Dispose en un bloque try/catch.To dispose of the type directly, call its Dispose method in a try/catch block. Para deshacerse de él indirectamente, use una construcción de lenguaje como using (en C#) o Using (en Visual Basic).To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). Para más información, vea la sección "Uso de objetos que implementan IDisposable" en el tema de la interfaz IDisposable.For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

Al producirse InsufficientMemoryException una excepción, una aplicación puede distinguir entre una estimación de que una operación no podrá completarse y una operación completada parcialmente que pueda haber dañado el estado de la aplicación.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. Esto permite a una aplicación reducir la frecuencia de una directiva de escala pesimista, lo que puede requerir la descarga del proceso actual AppDomain o el reciclaje.This allows an application to reduce the frequency of a pessimistic escalation policy, which may require unloading the current AppDomain or recycling the process.

MemoryFailPointcomprueba si hay suficiente memoria y espacio de direcciones virtuales consecutivas disponibles en todos los montones de recolección de elementos no utilizados, y puede aumentar el tamaño del archivo de intercambio.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. MemoryFailPointno garantiza la disponibilidad a largo plazo de la memoria durante la vigencia de la puerta, pero los llamadores siempre deben usar el Dispose método para asegurarse de que MemoryFailPoint se liberan los recursos asociados a.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.

Para usar una puerta de memoria, debe crear un MemoryFailPoint objeto y especificar el número de megabytes (MB) de memoria que se espera que use la siguiente operación.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. Si no hay suficiente memoria disponible, se InsufficientMemoryException produce una excepción.If enough memory is not available, an InsufficientMemoryException exception is thrown.

El parámetro del constructor debe ser un entero positivo.The parameter of the constructor must be a positive integer. Un valor negativo produce una ArgumentOutOfRangeException excepción.A negative value raises an ArgumentOutOfRangeException exception.

MemoryFailPointfunciona con una granularidad de 16 MB.MemoryFailPoint operates at a granularity of 16 MB. Los valores menores de 16 MB se tratan como 16 MB y otros valores se tratan como el siguiente múltiplo más grande de 16 MB.Any values smaller than 16 MB are treated as 16 MB, and other values are treated as the next largest multiple of 16 MB.

Constructores

MemoryFailPoint(Int32) MemoryFailPoint(Int32) MemoryFailPoint(Int32) MemoryFailPoint(Int32)

Inicializa una nueva instancia de la clase MemoryFailPoint, especificando la cantidad de memoria necesaria para que la ejecución sea correcta.Initializes a new instance of the MemoryFailPoint class, specifying the amount of memory required for successful execution.

Métodos

Dispose() Dispose() Dispose() Dispose()

Libera todos los recursos que usa MemoryFailPoint.Releases all resources used by the MemoryFailPoint.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()

Se asegura de que los recursos se liberan y que se llevan a cabo otras operaciones de limpieza cuando el recolector de elementos no utilizados recupere el objeto MemoryFailPoint.Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the MemoryFailPoint object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Seguridad

SecurityPermission
para llamar a código no administrado.for calling unmanaged code. Enumeración asociada: UnmanagedCode.Associated enumeration: UnmanagedCode. Acción de seguridad:LinkDemandSecurity action: LinkDemand

Se aplica a