OutOfMemoryException 類別

定義

當沒有足夠的記憶體繼續執行程式時,所擲回的例外狀況。The exception that is thrown when there is not enough memory to continue the execution of a program.

public ref class OutOfMemoryException : SystemException
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class OutOfMemoryException : SystemException
type OutOfMemoryException = class
    inherit SystemException
Public Class OutOfMemoryException
Inherits SystemException
繼承
OutOfMemoryException
衍生
屬性

備註

OutOfMemoryException會使用 HRESULT COR_E_OUTOFMEMORY,其值為0x8007000E。OutOfMemoryException uses the HRESULT COR_E_OUTOFMEMORY, which has the value 0x8007000E.

如需執行個體的初始屬性值的清單OutOfMemoryException,請參閱OutOfMemoryException建構函式。For a list of initial property values for an instance of OutOfMemoryException, see the OutOfMemoryException constructors.

注意

繼承Data屬性的值一律null為。The value of the inherited Data property is always null.

OutOfMemoryException例外狀況有兩個主要原因:An OutOfMemoryException exception has two major causes:

  • 您嘗試展開StringBuilder的物件超出其StringBuilder.MaxCapacity屬性所定義的長度。You are attempting to expand a StringBuilder object beyond the length defined by its StringBuilder.MaxCapacity property.

  • Common language runtime 無法配置足夠的連續記憶體來成功執行作業。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. 如需OutOfMemoryException例外狀況原因的詳細資訊,請參閱「記憶體不足」的 blog 文章未參考實體記憶體For more information on the cause of the OutOfMemoryException exception, see the blog post "Out of Memory" Does Not Refer to Physical Memory.

    這種類型OutOfMemoryException的例外狀況代表嚴重失敗。This type of OutOfMemoryException exception represents a catastrophic failure. 如果您選擇處理例外狀況,您應該包含catch Environment.FailFast呼叫方法的區塊來終止應用程式,並將專案加入至系統事件記錄檔,如下列範例所示。If you choose to handle the exception, you should include a catch block that calls the Environment.FailFast 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...
    
    Module Example
       Public Sub Main()
          Try
             ' Outer block to handle any unexpected exceptions.
             Try
                Dim s As String = "This"
                s = s.Insert(2, "is ")
    
                ' Throw an OutOfMemoryException exception.
                Throw New OutOfMemoryException()
             Catch e As ArgumentException
                Console.WriteLine("ArgumentException in String.Insert")
             End Try
             
             ' Execute program logic.
    
          Catch e As OutOfMemoryException
             Console.WriteLine("Terminating application unexpectedly...")
             Environment.FailFast(String.Format("Out of Memory: {0}",
                                                e.Message))
          End Try
       End Sub
    End Module
    ' 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:

您正在呼叫StringBuilder.Insert方法。You are calling the StringBuilder.Insert method.

您嘗試增加的StringBuilder物件長度超過其StringBuilder.MaxCapacity屬性所指定的大小。You are attempting to increase the length of a StringBuilder object beyond the size specified by its StringBuilder.MaxCapacity property. 下列範例說明當範例OutOfMemoryException嘗試插入可能導致物件的Length屬性StringBuilder.Insert(Int32, String, Int32)超過其最大容量的字串時,呼叫方法所擲回的例外狀況。The following example illustrates the OutOfMemoryException exception thrown by a call to the StringBuilder.Insert(Int32, String, Int32) method when the example tries to insert a string that would cause the object's 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.
Imports System.Text

Module Example
   Public Sub Main()
      Dim sb As New StringBuilder(15, 15)
      sb.Append("Substring #1 ")
      Try
         sb.Insert(0, "Substring #2 ", 1)
      Catch e As OutOfMemoryException
         Console.WriteLine("Out of Memory: {0}", e.Message)
      End Try
   End Sub
End Module
' 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:

您的應用程式會以32位進程的形式執行。Your app runs as a 32-bit process.

32位處理常式在32位系統上最多可以配置 2 GB 的虛擬使用者模式記憶體,而在64位系統上,則有4GB 的虛擬使用者模式記憶體。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. 這可能會使 common language runtime 更難以在需要大量配置時配置足夠的連續記憶體。This can make it more difficult for the common language runtime to allocate sufficient contiguous memory when a large allocation is needed. 相反地,64位進程可以配置最多8TB 的虛擬記憶體。In contrast, 64-bit processes can allocate up to 8TB of virtual memory. 若要解決此例外狀況,請將您的應用程式重新編譯成以64位平臺為目標。To address this exception, recompile your app to target a 64-bit platform. 如需在 Visual Studio 中以特定平臺為目標的詳細資訊,請參閱如何:將專案設定到目標平台For information on targeting specific platforms in Visual Studio, see How to: Configure Projects to Target Platforms.

您的應用程式正在洩漏未受管理的資源Your app is leaking unmanaged resources

雖然垃圾收集行程能夠釋放配置給 managed 類型的記憶體,但它並不會管理配置給非受控資源的記憶體,例如作業系統控制碼(包括檔案的控制碼、記憶體對應檔案、管道、登錄機碼和等候控制碼)和由 Windows API 呼叫直接配置的記憶體區塊,或呼叫記憶體配置函式( malloc例如)。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. 使用非受控資源的類型會IDisposable執行介面。Types that consume unmanaged resources implement the IDisposable interface.

如果您取用的類型使用非受控資源,您應該在完成使用時,務必IDisposable.Dispose呼叫其方法。If you are consuming a type that uses unmanaged resources, you should be sure to call its IDisposable.Dispose method when you have finished using it. (有些型別也Close會實作用Dispose于方法的函式中相同的方法)。如需詳細資訊,請參閱使用執行 IDisposable 的物件主題。(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. 如需詳細資訊,請參閱執行 Dispose 方法Object.FinalizeFor more information, see Implementing a Dispose method and Object.Finalize.

您嘗試在64位進程中建立大型陣列You are attempting to create a large array in a 64-bit process

根據預設,.NET Framework 中的 common language runtime 不允許大小超過2GB 的單一物件。By default, the common language runtime in .NET Framework does not allow single objects whose size exceeds 2GB. 若要覆寫此預設值,您可以使用 [ <gcallowverylargeobjects> >設定檔] 設定,以啟用總計大小超過 2 GB 的陣列。To override this default, you can use the <gcAllowVeryLargeObjects> configuration file setting to enable arrays whose total size exceeds 2 GB. 在 .NET Core 上,預設會啟用大於 2 GB 的陣列支援。On .NET Core, support for arrays of greater than 2 GB is enabled by default.

您在記憶體中使用非常大型的資料集(例如陣列、集合或資料庫資料集)。You are working with very large sets of data (such as arrays, collections, or database data sets) in memory.

當位於記憶體中的資料結構或資料集變得很大時,common language runtime 無法為其配置足夠的連續記憶體, OutOfMemoryException會產生例外狀況。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 OutOfMemoryException exception results.

若要避免OutOfMemoryException發生例外狀況,您必須修改應用程式,使記憶體中的資料較少,或將資料分割成需要較小記憶體配置的區段。To prevent the 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.

  • 如果您使用的是大型陣列或大小會導致OutOfMemoryException例外狀況的其他集合物件,您應該將應用程式修改成以子集的方式處理資料,而不是一次使用。If you are using large arrays or other collection objects whose size results in an OutOfMemoryException exception, you should modify your application to work the data in subsets rather than to work with it all at once.

下列範例會取得包含200000000浮點值的陣列,然後計算其平均值。The following example gets a array that consists of 200 million floating-point values and then calculates their mean. 範例的輸出顯示,因為範例會在計算平均值之前將整個陣列儲存在記憶體中, OutOfMemoryException所以會擲回。The output from the example shows that, because the example stores the entire array in memory before it calculates the mean, an OutOfMemoryException 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.
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim values() As Double = GetData()
      ' Compute mean.
      Console.WriteLine("Sample mean: {0}, N = {1}",
                        GetMean(values), values.Length)
   End Sub
   
   Private Function GetData() As Double()
      Dim rnd As New Random()
      Dim values As New List(Of Double)()
      For ctr As Integer = 1 To 200000000
         values.Add(rnd.NextDouble)
         If ctr Mod 10000000 = 0 Then
            Console.WriteLine("Retrieved {0:N0} items of data.",
                              ctr)
         End If
      Next
      Return values.ToArray()
   End Function
   
   Private Function GetMean(values() As Double) As Double
      Dim sum As Double = 0
      For Each value In values
         sum += value
      Next
      Return sum / values.Length
   End Function
End Module
' 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.

下列範例會處理內OutOfMemoryException送資料,而不將整個資料集儲存在記憶體中,藉此消除例外狀況,視需要將資料序列化至檔案,以允許進一步處理(在範例中,這些程式列會加上批註,在此情況下,它們會產生大小大於 1 GB 的檔案,並將計算出的平均值和案例數目傳回給呼叫的常式。The following example eliminates the 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
Imports System.IO

Module Example
   Public Sub Main()
      Dim result As Tuple(Of Double, Long) = GetResult()
      Console.WriteLine("Sample mean: {0}, N = {1:N0}",
                        result.Item1, result.Item2)
   End Sub

   Private Function GetResult As Tuple(Of Double, Long)
      Dim chunkSize As Integer = 50000000
      Dim nToGet As Integer = 200000000
      Dim rnd As New Random()
'       Dim fs As New FileStream(".\data.bin", FileMode.Create)
'       Dim bin As New BinaryWriter(fs)
'       bin.Write(CInt(0))
      Dim n As Integer
      Dim sum As Double
      For outer As Integer = 0 To CInt(Math.Ceiling(nToGet/chunkSize) - 1)
         For inner = 0 To Math.Min(nToGet - n - 1, chunkSize - 1)
            Dim value As Double = rnd.NextDouble()
            sum += value
            n += 1
'            bin.Write(value)
         Next
      Next
'       bin.Seek(0, SeekOrigin.Begin)
'       bin.Write(n)
'       bin.Close()
      Return New Tuple(Of Double, Long)(sum/n, n)
   End Function
End Module
' 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. 但是對於大型字串或非常大量的串連作業,字串串連可能會導致大量的記憶體配置和記憶體片段、效能不佳,以及可能OutOfMemoryException的例外狀況。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 OutOfMemoryException exceptions.

串連大型字串或執行大量的串連作業時,您應該使用StringBuilder類別,而不是String類別。When concatenating large strings or performing a large number of concatenation operations, you should use the StringBuilder class instead of the String class. 當您完成操作字串時,藉由StringBuilder StringBuilder.ToString呼叫方法,將實例轉換成字串。When you have finished manipulating the string, convert the StringBuilder instance to a string by calling the 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. 如果您已在記憶體中釘選大量物件(例如,藉由使用中fixed C#的語句, GCHandle.Alloc(Object, GCHandleType)或藉由呼叫具有控制碼類型的GCHandleType.Pinned方法),您可以執行下列動作來OutOfMemoryException處理例外狀況。If you've pinned a large number of objects in memory, for example by using the fixed statement in C# or by calling the GCHandle.Alloc(Object, GCHandleType) method with a handle type of GCHandleType.Pinned, you can do the following to address the OutOfMemoryException exception.

  • 評估每個物件是否真的需要固定,Evaluate whether each object really needs to be pinned,

  • 請確定每個物件都已儘快取消固定。Ensure that each object is unpinned as soon as possible.

  • 請確定每次呼叫GCHandle.Alloc(Object, GCHandleType)方法來釘選記憶體時,都有對應的GCHandle.Free方法呼叫來解除固定該記憶體。Make sure that each call to the GCHandle.Alloc(Object, GCHandleType) method to pin memory has a corresponding call to the GCHandle.Free method to unpin that memory.

下列 Microsoft 中繼(MSIL)指令會擲OutOfMemoryException回例外狀況:The following Microsoft intermediate (MSIL) instructions throw an OutOfMemoryException exception:

建構函式

OutOfMemoryException()

初始化 OutOfMemoryException 類別的新執行個體。Initializes a new instance of the OutOfMemoryException class.

OutOfMemoryException(SerializationInfo, StreamingContext)

使用序列化資料,初始化 OutOfMemoryException 類別的新執行個體。Initializes a new instance of the OutOfMemoryException class with serialized data.

OutOfMemoryException(String)

使用指定的錯誤訊息,初始化 OutOfMemoryException 類別的新執行個體。Initializes a new instance of the OutOfMemoryException class with a specified error message.

OutOfMemoryException(String, Exception)

使用指定的錯誤訊息以及造成此例外狀況的內部例外狀況的參考,初始化 OutOfMemoryException 類別的新執行個體。Initializes a new instance of the OutOfMemoryException class with a specified error message and a reference to the inner exception that is the cause of this exception.

屬性

Data

取得提供例外狀況之其他使用者定義相關資訊的索引鍵/值組集合。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(繼承來源 Exception)
HelpLink

取得或設定與這個例外狀況相關聯的說明檔連結。Gets or sets a link to the help file associated with this exception.

(繼承來源 Exception)
HResult

取得或設定 HRESULT,它是指派給特定例外狀況的編碼數值。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(繼承來源 Exception)
InnerException

取得造成目前例外狀況的 Exception 執行個體。Gets the Exception instance that caused the current exception.

(繼承來源 Exception)
Message

取得描述目前例外狀況的訊息。Gets a message that describes the current exception.

(繼承來源 Exception)
Source

取得或設定造成錯誤的應用程式或物件的名稱。Gets or sets the name of the application or the object that causes the error.

(繼承來源 Exception)
StackTrace

取得呼叫堆疊上即時運算框架的字串表示。Gets a string representation of the immediate frames on the call stack.

(繼承來源 Exception)
TargetSite

取得擲回目前例外狀況的方法。Gets the method that throws the current exception.

(繼承來源 Exception)

方法

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetBaseException()

在衍生類別中覆寫時,傳回一或多個後續的例外狀況的根本原因 ExceptionWhen overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(繼承來源 Exception)
GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetObjectData(SerializationInfo, StreamingContext)

在衍生類別中覆寫時,使用例外狀況的資訊設定 SerializationInfoWhen overridden in a derived class, sets the SerializationInfo with information about the exception.

(繼承來源 Exception)
GetType()

取得目前執行個體的執行階段類型。Gets the runtime type of the current instance.

(繼承來源 Exception)
MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

建立並傳回目前例外狀況的字串表示。Creates and returns a string representation of the current exception.

(繼承來源 Exception)

事件

SerializeObjectState

當例外狀況序列化,以建立包含例外狀況相關序列化資料的例外狀況狀態物件時,就會發生此事件。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(繼承來源 Exception)

適用於

另請參閱