Questo articolo è stato tradotto automaticamente. Per visualizzare l'articolo in inglese, selezionare la casella di controllo Inglese. È possibile anche visualizzare il testo inglese in una finestra popup posizionando il puntatore del mouse sopra il testo.
Traduzione
Inglese

Classe OutOfMemoryException

 

L'eccezione che viene generata quando non c'è abbastanza memoria disponibile per continuare l'esecuzione di un programma.

Spazio dei nomi:   System
Assembly:  mscorlib (in mscorlib.dll)

System.Object
  System.Exception
    System.SystemException
      System.OutOfMemoryException
        System.InsufficientMemoryException

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class OutOfMemoryException : SystemException

NomeDescrizione
System_CAPS_pubmethodOutOfMemoryException()

Inizializza una nuova istanza della classe OutOfMemoryException.

System_CAPS_protmethodOutOfMemoryException(SerializationInfo, StreamingContext)

Inizializza una nuova istanza della classe OutOfMemoryException con dati serializzati.

System_CAPS_pubmethodOutOfMemoryException(String)

Inizializza una nuova istanza della classe OutOfMemoryException con un messaggio di errore specificato.

System_CAPS_pubmethodOutOfMemoryException(String, Exception)

Inizializza una nuova istanza della classe OutOfMemoryException con un messaggio di errore specificato e un riferimento all'eccezione interna che è la causa dell'eccezione corrente.

NomeDescrizione
System_CAPS_pubpropertyData

Ottiene una collezione di coppie chiave/valore che forniscono ulteriori informazioni definite dall'utente sull'eccezione. (Ereditato da Exception.)

System_CAPS_pubpropertyHelpLink

Ottiene o imposta un collegamento al file della Guida associato all'eccezione.(Ereditato da Exception.)

System_CAPS_pubpropertyHResult

Ottiene o imposta HRESULT, un valore numerico codificato che viene assegnato ad una specifica eccezione. (Ereditato da Exception.)

System_CAPS_pubpropertyInnerException

Ottiene l'istanza di Exception che ha causato l'eccezione corrente.(Ereditato da Exception.)

System_CAPS_pubpropertyMessage

Ottiene un messaggio che descrive l'eccezione corrente.(Ereditato da Exception.)

System_CAPS_pubpropertySource

Ottiene o imposta il nome dell'oggetto o dell'applicazione che ha generato l'errore.(Ereditato da Exception.)

System_CAPS_pubpropertyStackTrace

Ottiene una rappresentazione in forma di stringa dei frame nello stack di chiamate. (Ereditato da Exception.)

System_CAPS_pubpropertyTargetSite

Ottiene il metodo che ha generato l'eccezione corrente. (Ereditato da Exception.)

NomeDescrizione
System_CAPS_pubmethodEquals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente. (Ereditato da Object.)

System_CAPS_protmethodFinalize()

Consente a un oggetto di provare a liberare risorse ed eseguire altre operazioni di pulizia prima che l'oggetto stesso venga reclamato dalla procedura di Garbage Collection. (Ereditato da Object.)

System_CAPS_pubmethodGetBaseException()

Quando ne viene eseguito l'override in una classe derivata, restituisce l'Exception che è la causa radice di una o più eccezioni successive.(Ereditato da Exception.)

System_CAPS_pubmethodGetHashCode()

Funge da funzione hash predefinita.(Ereditato da Object.)

System_CAPS_pubmethodGetObjectData(SerializationInfo, StreamingContext)

Quando ne viene eseguito l'override in una classe derivata, imposta il controllo SerializationInfo con le informazioni sull'eccezione.(Ereditato da Exception.)

System_CAPS_pubmethodGetType()

Ottiene il tipo di runtime dell'istanza corrente.(Ereditato da Exception.)

System_CAPS_protmethodMemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.(Ereditato da Object.)

System_CAPS_pubmethodToString()

Crea e restituisce una rappresentazione di stringa dell'eccezione corrente.(Ereditato da Exception.)

NomeDescrizione
System_CAPS_proteventSerializeObjectState

Si verifica quando un'eccezione viene serializzata per creare un oggetto di stato eccezione contenente i dati serializzati relativi all'eccezione.(Ereditato da Exception.)

An T:System.OutOfMemoryException exception has two major causes:

  • You are attempting to expand a T:System.Text.StringBuilder object beyond the length defined by its P:System.Text.StringBuilder.MaxCapacity property.

  • The common language runtime cannot allocate enough contiguous memory to successfully perform an operation. This exception can be thrown by any property assignment or method call that requires a memory allocation. For more information on the cause of the T:System.OutOfMemoryException exception, see "Out of Memory" Does Not Refer to Physical Memoryhttp://blogs.msdn.com/b/ericlippert/archive/2009/06/08/out-of-memory-does-not-refer-to-physical-memory.aspx.

    This type of T:System.OutOfMemoryException exception represents a catastrophic failure. If you choose to handle the exception, you should include a catch block that calls the M:System.Environment.FailFast(System.String) method to terminate your app and add an entry to the system event log, as the following example does.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          try {
             // Outer block to handle any unexpected exceptions.
             try {
                string s = "This";
                s = s.Insert(2, "is ");
    
                // Throw an OutOfMemoryException exception.
                throw new OutOfMemoryException();
             }
             catch (ArgumentException) {
                Console.WriteLine("ArgumentException in String.Insert");
             }
    
             // Execute program logic.
          }
          catch (OutOfMemoryException e) {
             Console.WriteLine("Terminating application unexpectedly...");
             Environment.FailFast(String.Format("Out of Memory: {0}",
                                                e.Message));
          }
       }
    }
    // The example displays the following output:
    //        Terminating application unexpectedly...
    

Some of the conditions under which the exception is thrown and the actions you can take to eliminate it include the following:

You are calling the M:System.Text.StringBuilder.Insert(System.Int32,System.String) method.

You are attempting to increase the length of a T:System.Text.StringBuilder object beyond the size specified by its P:System.Text.StringBuilder.MaxCapacity property. The following example illustrates the T:System.OutOfMemoryException exception thrown by a call to the M:System.Text.StringBuilder.Insert(System.Int32,System.String,System.Int32) method when the example tries to insert a string that would cause the object's P:System.Text.StringBuilder.Length property to exceed its maximum capacity.

using System;
using System.Text;

public class Example
{
   public static void Main()
   {
      StringBuilder sb = new StringBuilder(15, 15);
      sb.Append("Substring #1 ");
      try {
         sb.Insert(0, "Substring #2 ", 1);
      }
      catch (OutOfMemoryException e) {
         Console.WriteLine("Out of Memory: {0}", e.Message);
      }
   }
}
// The example displays the following output:
//    Out of Memory: Insufficient memory to continue the execution of the program.

You can do either of the following to address the error:

  • Replace the call to the M:System.Text.StringBuilder.#ctor(System.Int32,System.Int32) constructor with a call any other T:System.Text.StringBuilder constructor overload. The maximum capacity of your T:System.Text.StringBuilder object will be set to its default value, which is F:System.Int32.MaxValue.

  • Call the M:System.Text.StringBuilder.#ctor(System.Int32,System.Int32) constructor with a maxCapacity value that is large enough to accommodate any expansions to the T:System.Text.StringBuilder object.

Your app runs as a 32-bit process.

32-bit processes can allocate a maximum of 2GB of virtual user-mode memory on 32-bit systems, and 4GB of virtual user-mode memory on 64-bit systems. This can make it more difficult for the common language runtime to allocate sufficient contiguous memory when a large allocation is needed. In contrast, 64-bit processes can allocate up to 8TB of virtual memory. To address this exception, recompile your app to target a 64-bit platform. For information on targeting specific platforms in Visual Studio, see How to: Configure Projects to Target Platforms.

Your app is leaking unmanaged resources

Although the garbage collector is able to free memory allocated to managed types, it does not manage memory allocated to unmanaged resources such as operating system handles (including handles to files, memory-mapped files, pipes, registry keys, and wait handles) and memory blocks allocated directly by Windows API calls or by calls to memory allocation functions such as malloc. Types that consume unmanaged resources implement the T:System.IDisposable interface.

If you are consuming a type that uses unmanaged resources, you should be sure to call its M:System.IDisposable.Dispose method when you have finished using it. (Some types also implement a Close method that is identical in function to a Dispose method.) For more information, see the Using Objects That Implement IDisposable topic.

If you have created a type that uses unmanaged resources, make sure that you have implemented the Dispose pattern and, if necessary, supplied a finalizer. For more information, see the Dispose Pattern, Implementing a Dispose Method, and M:System.Object.Finalize topics.

You are attempting to create a large array in a 64-bit process.

By default, the common language runtime does not allow single objects whose size exceeds 2GB. To override this default, you can use the configuration file setting to enable arrays whose total size exceeds 2 GB.

You are working with very large sets of data (such as arrays, collections, or database data sets) in memory.

When data structures or data sets that reside in memory become so large that the common language runtime is unable to allocate enough contiguous memory for them, an T:System.OutOfMemoryException exception results.

To prevent the T:System.OutOfMemoryException exceptions, you must modify your application so that less data is resident in memory, or the data is divided into segments that require smaller memory allocations. For example:

  • If you are retrieving all of the data from a database and then filtering it in your app to minimize trips to the server, you should modify your queries to return only the subset of data that your app needs. When working with large tables, multiple queries are almost always more efficient than retrieving all of the data in a single table and then manipulating it.

  • If you are executing queries that users create dynamically, you should ensure that the number of records returned by the query is limited.

  • If you are using large arrays or other collection objects whose size results in an T:System.OutOfMemoryException exception, you should modify your application to work the data in subsets rather than to work with it all at once.

The following example gets a array that consists of 200 million floating-point values and then calculates their mean. The output from the example shows that, because the example stores the entire array in memory before it calculates the mean, an T:System.OutOfMemoryException is is thrown.

using System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
      Double[] values = GetData();
      // Compute mean.
      Console.WriteLine("Sample mean: {0}, N = {1}",
                        GetMean(values), values.Length);
   }

   private static Double[] GetData()
   {
      Random rnd = new Random();
      List<Double> values = new List<Double>();
      for (int ctr = 1; ctr <= 200000000; ctr++) {
         values.Add(rnd.NextDouble());
         if (ctr % 10000000 == 0)
            Console.WriteLine("Retrieved {0:N0} items of data.",
                              ctr);
      }
      return values.ToArray();
   }

   private static Double GetMean(Double[] values)
   {
      Double sum = 0;
      foreach (var value in values)
         sum += value;

      return sum / values.Length;
   }
}
// The example displays output like the following:
//    Retrieved 10,000,000 items of data.
//    Retrieved 20,000,000 items of data.
//    Retrieved 30,000,000 items of data.
//    Retrieved 40,000,000 items of data.
//    Retrieved 50,000,000 items of data.
//    Retrieved 60,000,000 items of data.
//    Retrieved 70,000,000 items of data.
//    Retrieved 80,000,000 items of data.
//    Retrieved 90,000,000 items of data.
//    Retrieved 100,000,000 items of data.
//    Retrieved 110,000,000 items of data.
//    Retrieved 120,000,000 items of data.
//    Retrieved 130,000,000 items of data.
//
//    Unhandled Exception: OutOfMemoryException.

The following example eliminates the T:System.OutOfMemoryException exception by processing the incoming data without storing the entire data set in memory, serializing the data to a file if necessary to permit further processing (these lines are commented out in the example, since in this case they produce a file whose size is greater than 1GB), and returning the calculated mean and the number of cases to the calling routine.

using System;
using System.IO;

public class Example
{
   public static void Main()
   {
      Tuple<Double, long> result = GetResult();
      Console.WriteLine("Sample mean: {0}, N = {1:N0}",
                        result.Item1, result.Item2);
   }

   private static Tuple<Double, long> GetResult()
   {
      int chunkSize = 50000000;
      int nToGet = 200000000;
      Random rnd = new Random();
      // FileStream fs = new FileStream(@".\data.bin", FileMode.Create);
      // BinaryWriter bin = new BinaryWriter(fs);
      // bin.Write((int)0);
      int n = 0;
      Double sum = 0;
      for (int outer = 0;
           outer <= ((int) Math.Ceiling(nToGet * 1.0 / chunkSize) - 1);
           outer++) {
         for (int inner = 0;
              inner <= Math.Min(nToGet - n - 1, chunkSize - 1);
              inner++) {
            Double value = rnd.NextDouble();
            sum += value;
            n++;
            // bin.Write(value);
         }
      }
      // bin.Seek(0, SeekOrigin.Begin);
      // bin.Write(n);
      // bin.Close();
      return new Tuple<Double, long>(sum/n, n);
   }
}
// The example displays output like the following:
//    Sample mean: 0.500022771458399, N = 200,000,000
You are repeatedly concatenating large strings.

Because strings are immutable, each string concatenation operation creates a new string. The impact for small strings, or for a small number of concatenation operations, is negligible. But for large strings or a very large number of concatenation operations, string concatenation can lead to a large number of memory allocations and memory fragmentation, poor performance, and possibly T:System.OutOfMemoryException exceptions.

When concatenating large strings or performing a large number of concatenation operations, you should use the T:System.Text.StringBuilder class instead of the T:System.String class. When you have finished manipulating the string, convert the T:System.Text.StringBuilder instance to a string by calling the M:System.Text.StringBuilder.ToString method.

You pin a large number of objects in memory.

Pinning a large number of objects in memory for long periods can make it difficult for the garbage collector to allocate contiguous blocks of memory. If you've pinned a large number of objects in memory, for example by using the fixed statement in C# or by calling the M:System.Runtime.InteropServices.GCHandle.Alloc(System.Object,System.Runtime.InteropServices.GCHandleType) method with a handle type of F:System.Runtime.InteropServices.GCHandleType.Pinned, you can do the following to address the T:System.OutOfMemoryException exception.

  • Evaluate whether each object really needs to be pinned,

  • Ensure that each object is unpinned as soon as possible.

  • Make sure that each call to the M:System.Runtime.InteropServices.GCHandle.Alloc(System.Object,System.Runtime.InteropServices.GCHandleType) method to pin memory has a corresponding call to the M:System.Runtime.InteropServices.GCHandle.Free method to unpin that memory.

The following Microsoft intermediate (MSIL) instructions throw an T:System.OutOfMemoryException exception:

OutOfMemoryException uses the HRESULT COR_E_OUTOFMEMORY, which has the value 0x8007000E.

For a list of initial property values for an instance of T:System.OutOfMemoryException, see the M:System.OutOfMemoryException.#ctor constructors.

System_CAPS_noteNota

The value of the inherited P:System.Exception.Data property is always null.

Universal Windows Platform
Disponibile da 8
.NET Framework
Disponibile da 1.1
Libreria di classi portabile
Supportato in: piattaforme .NET portabili
Silverlight
Disponibile da 2.0
Windows Phone Silverlight
Disponibile da 7.0
Windows Phone
Disponibile da 8.1

I membri statici pubblici ( Condiviso in Visual Basic) di questo tipo è thread safe. Non tutti i membri di istanza sono garantiti come thread safe.

Torna all'inizio
Mostra: