问题
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