MemoryFailPoint(Int32) 建構函式

定義

初始化 MemoryFailPoint 類別的新執行個體,並指定順利執行所需的記憶體容量。

public:
 MemoryFailPoint(int sizeInMegabytes);
public MemoryFailPoint (int sizeInMegabytes);
[System.Security.SecurityCritical]
public MemoryFailPoint (int sizeInMegabytes);
new System.Runtime.MemoryFailPoint : int -> System.Runtime.MemoryFailPoint
[<System.Security.SecurityCritical>]
new System.Runtime.MemoryFailPoint : int -> System.Runtime.MemoryFailPoint
Public Sub New (sizeInMegabytes As Integer)

參數

sizeInMegabytes
Int32

所需的記憶體大小,以 MB 為單位。 這個必須是正值。

屬性

例外狀況

指定的記憶體大小為負數。

記憶體不足,無法開始執行閘道所保護的程式碼。

範例

下列範例示範如何在執行時判斷方法所需的記憶體數量。 此程式碼範例是提供給 類別之較大範例的 MemoryFailPoint 一部分。

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;
}

備註

應用程式用來處理工作專案的記憶體數量可以經驗判斷。 若要估計應用程式處理要求所需的記憶體數量,請考慮使用 GC.GetTotalMemory 方法來判斷處理工作專案的方法之前和之後可用的記憶體數量。 MemoryFailPoint如需動態判斷 參數值的 sizeInMegabytes 程式碼範例,請參閱 類別。

適用於