您可以使用WMI檢索Win32_OperatingSystem
class的實例和基本內存計算關閉FreePhysicalMemory
或TotalVisibleMemorySize
屬性:
static ulong GetAvailableMemoryKilobytes()
{
const string memoryPropertyName = "FreePhysicalMemory";
using (ManagementObject operatingSystem = new ManagementObject("[email protected]"))
return (ulong) operatingSystem[memoryPropertyName];
}
static ulong GetTotalMemoryKilobytes()
{
const string memoryPropertyName = "TotalVisibleMemorySize";
using (ManagementObject operatingSystem = new ManagementObject("[email protected]"))
return (ulong) operatingSystem[memoryPropertyName];
}
那麼這兩種方法的結果傳遞給方法像這樣規模的您讀取緩衝區的大小到本地機器的內存:
static int GetBufferSize(ulong memoryKilobytes)
{
const int bufferStepSize = 256; // 256 kilobytes of buffer...
const int memoryStepSize = 128 * 1024;// ...for every 128 megabytes of memory...
const int minBufferSize = 512; // ...no less than 512 kilobytes...
const int maxBufferSize = 10 * 1024; // ...no more than 10 megabytes
int bufferSize = bufferStepSize * ((int) memoryKilobytes/memoryStepSize);
bufferSize = Math.Max(bufferSize, minBufferSize);
bufferSize = Math.Min(bufferSize, maxBufferSize);
return bufferSize;
}
顯然,增加256 KB的緩衝區大小每128 MB的RAM似乎有點傻,但這些數字都只是例子如果你真的想這麼做,你如何擴展你的緩衝區大小。除非你一次讀取很多很多的文件,否則擔心一個幾百KB或幾MB的緩衝區可能比它的價值更麻煩。你可能比基準測試更好,看看哪種大小的緩衝區能夠提供最佳性能(可能不需要像你想象的那麼大)並使用它。
現在,你可以簡單地更新你的代碼是這樣的:
ulong memoryKilobytes =
GetAvailableMemoryKilobytes();
// ...or GetTotalMemoryKilobytes();
int bufferSize = GetBufferSize(memoryKilobytes);
using (FileStream TheFileStream = new FileStream(FilePath.Text, FileMode.Open))
{
byte[] FileArray = new byte[bufferSize];
int readCount;
while ((readCount = TheFileBinary.Read(FileArray, 0, bufferSize)) > 0)
{
// Call a method here, passing FileArray as a parameter
}
}
'想使加密algorithm'這可能是一個錯誤。安全加密是_hard_。 – SLaks 2012-03-12 18:54:11
你要求的〜10MB是一個相當小的數額。你爲什麼在這裏擔心記憶問題?你遇到問題了嗎?你預計未來某些10MB的設備會遇到什麼問題? – dlev 2012-03-12 18:55:41
(可以說)_better_方法是製作你自己的Stream。 – 2012-03-12 18:59:21