我正在用 C# 重新编写一个应用程序以在 Windows CE 上运行,但是,我的机器内存不足。
所以我需要分配适量的程序内存和存储内存。但是我不能在每次重启时手动分配它,然后我找到了 SetSystemMemoryDivision() 函数。
我所做的分配代码基本上如下:
public void setmemory()
{
//Checks if the memory is correctly allocated
while (storage_page != 800)
{
//Set the memory to 800 pages of 4096 bytes each ( = 800 * 4kB 3.200Kb )
storage_page = 800;
//Writes the seted memory
SetSystemMemoryDivision(storage_page);
Thread.Sleep(200);
//Read system memory
GetSystemMemoryDivision(ref storage_page, ref ram_page, ref page_size);
}
}
callmenu();
(功能正常,但如果我之前没有手动分配可接受的内存值,我的应用程序仍然会卡住机器。
我怎样才能确保在运行任何可以停止机器的进程之前分配内存?)下面的更正:
我对这个问题的看法是错误的。实际上,只有在我的设备与计算机连接并通过 Visual Studio 运行调试后,该应用程序才会运行。每次我重新启动设备并尝试运行我的应用程序而不在 PC 上调试它时,系统都会停止。即使我手动分配内存。因此,系统似乎卡住了,因为程序试图分配超过 32MB 的可用空间。
最佳答案
这是一项艰巨的挑战。首先,您需要知道您的应用程序运行需要多少内存。知道这一点的唯一方法就是测试、测试和测试。然后添加应急金额。
获得该数字后,您可以在应用程序启动的早期调用 SetSystemMemoryDivision
,在它开始在堆上分配大量内容并耗尽内存之前。在 static void Main()
的早期,在调用 Application.Run()
之前就是典型的候选位置。
如果“需要的数量”未知,你总是可以创建一个后台服务线程,定期检查可用内存并重新调整内存划分,以尽量始终有空间供 GC 堆增长。这更难实现,但并非不可能。
这是一个示例计时器过程,我用它来将内存保持在可用内存的 95%(它将以整数形式存储在 HoldProgramMemoryPercent
中,例如 95):
private void TimerProc(object state)
{
// check and adjust memory
var total = MemoryManagement.SystemProgramMemory + MemoryManagement.SystemStorageMemory;
var before = (MemoryManagement.SystemProgramMemory / (float)total) * 100;
var requiredStorage = (int)(((100 - HoldProgramMemoryPercent) / 100f) * total);
if ((requiredStorage != m_lastLevel) && (requiredStorage != MemoryManagement.SystemStorageMemory))
{
MemoryManagement.SystemStorageMemory = requiredStorage;
var after = (MemoryManagement.SystemProgramMemory / (float)total) * 100;
Debug.WriteLine(string.Format("Program memory changed from {0}% to {1}%", before, after));
m_lastLevel = requiredStorage;
}
Debug.WriteLine(string.Format("Memory load is at {0}%", MemoryManagement.MemoryLoad));
}
关于c# - 在 WinCE 上运行我的应用程序之前如何分配程序内存和存储空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21735509/