C# WebClient Memory Usage

ぃ、小莉子 提交于 2019-12-20 02:37:10

问题


I am using WebClient,DownloadString("http://example.com/string.txt"); When I call it the memory jumps up, but never goes down again, and since I need 2-3 different strings downloaded from the web the memory jumps up quite much.

I am new to C# and still learning, but is there anyway to clear the memory after I have downloaded the string from the web? If not, do you know any other methods I can use to read from the web wich uses less memory?

Thanks


回答1:


WebClient implements IDisposable, so your code should look like this:

string result;
using (WebClient client = new WebClient())
{
    result = client.DownloadString("http://example.com/string.txt");
}
Console.WriteLine(result);

This will make sure that most resources used by the WebClient instance are released.

The rest will eventually be cleaned up by the Garbage Collector. You don't need worry about this.




回答2:


"Memory usage" as displayed by tools like Taskmgr.exe or ProcExp.exe tells you squat about the actual memory in use by a program. When virtual memory is released by the garbage collector, the free space is almost never returned to the operating system. It gets added to a list of free blocks, ready for re-use by the next allocation. The odds that the free blocks coalesce back into a range of pages that can be freed are quite small.

This is never a real problem, this is virtual memory. Another way to make you feel good quickly is to minimize the main window of the program. That trims the working set, the amount of RAM in use.



来源:https://stackoverflow.com/questions/3383167/c-sharp-webclient-memory-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!