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

需要的内存大小(以兆字节为单位)。 这必须是一正值。

属性

例外

指定的内存大小为负或 0。

没有足够的内存来开始执行由门保护的代码。

示例

以下示例演示如何确定方法在执行时所需的内存量。 此代码示例是为 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代码示例,请参阅 类。

适用于