問題描述
在建立App Service服務的時候,根據定價層不同,記憶體使用的最大值也有不同。但在實際測試中,發現記憶體最大隻能佔用2GB左右,
而定價層中記憶體分配明明是大於2GB(比如B3定價層的記憶體為7GB), 這是一種什麼情況呢?
在App Service中Kudu工具上,檢視程序分配的記憶體大小:
問題解答
使用一段簡短C#程式碼來進行驗證,程式碼是一個迴圈,根據URL中輸入的數字,迴圈建立多個100MB大小的物件.
var builder = WebApplication.CreateBuilder(args); // Add services to the container. var app = builder.Build(); app.MapGet("/oom/{objs}", (string objs) => { int objunmbers = int.Parse(objs); try { byte[][] largeArray = new byte[objunmbers][]; for (int i = 0; i < objunmbers; i++) { largeArray[i] = new byte[1024 * 1024 * 100]; // 每個物件佔用100MB } return "成功建立大陣列物件: " + objs; } catch (OutOfMemoryException) { return "記憶體不足,無法建立大陣列物件"; } }); app.Run();
程式碼本地除錯,可以看見應用佔用記憶體直線上漲:
部署到Azure App Service後,同樣透過Kudu站點Process資訊,發現記憶體的佔用的確只有2GB左右,但請求需要更多記憶體資源時,頁面返回:記憶體不足,無法建立大陣列物件
這是因為App Service for Windows預設使用32位作業系統,最大記憶體只能分配2GB。
當主動修改位64位後,App Service 記憶體就可以佔用到定價層所允許的最大值!
如B3的定價層在Kudu中檢視到w3wp.exe程序分配的記憶體達到了6GB
根據以上測驗,當使用App Service記憶體沒有達到預期的值,且應用異常日誌出現OutOfMemory時,就需要檢查Platform的設定是否位64bit。
參考資料
I see the message "Worker Process requested recycle due to 'Percent Memory' limit." How do I address this issue?
https://learn.microsoft.com/en-us/troubleshoot/azure/app-service/web-apps-performance-faqs#i-see-the-message-worker-process-requested-recycle-due-to-percent-memory-limit-how-do-i-address-this-issue
The maximum available amount of memory for a 32-bit process (even on a 64-bit operating system) is 2 GB. By default, the worker process is set to 32-bit in App Service (for compatibility with legacy web applications).
Consider switching to 64-bit processes so you can take advantage of the additional memory available in your Web Worker role. This triggers a web app restart, so schedule accordingly.
Also note that a 64-bit environment requires a Basic or Standard service plan. Free and Shared plans always run in a 32-bit environment.