MemoryFailPoint(Int32) 建構函式
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
初始化該類別的新實例 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 為單位。 這必須是正值。
- 屬性
例外狀況
指定的記憶體大小為負數或 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 方法來判斷呼叫處理該工作項目的方法前後可用的記憶體量。 請參考 class 這個 MemoryFailPoint 程式範例,該範例會動態決定參數的值 sizeInMegabytes 。