views:

77

answers:

2

Hello, 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

+2  A: 

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.

dtb
Well, in this case I doubt it will change anything, as the returned string from `DownloadString` isn't exactly an unmanaged resource that will be freed on `Dispose()`. Good general advice to always wrap `IDisposable` in `using`, though.
Joey
@Johannes Rössel: It's not the return value that is disposed by WebClient, but the internal objects that are used by it, e.g., HttpWebRequest/HttpWebResponse objects. There is a reason why WebClient implements IDisposable, because if there wasn't, it wouldn't implement it.
dtb
As I am new to C#, can you explain this IDisposable thing?
PixL
+1  A: 

"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.

Hans Passant