简体   繁体   English

C#WebClient内存使用情况

[英]C# WebClient Memory Usage

I am using WebClient,DownloadString(" http://example.com/string.txt "); 我正在使用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. 当我调用它时,内存会跳起来,但永远不会再次下降,因为我需要从网上下载2-3个不同的字符串,所以内存会大大增加。

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? 我是C#的新手并且还在学习,但是从网上下载字符串之后是否还要清除内存? If not, do you know any other methods I can use to read from the web wich uses less memory? 如果没有,你知道我可以使用任何其他方法从网上阅读使用更少的内存吗?

Thanks 谢谢

WebClient implements IDisposable , so your code should look like this: WebClient实现了IDisposable ,因此您的代码应如下所示:

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. 这将确保释放WebClient实例使用的大多数资源。

The rest will eventually be cleaned up by the Garbage Collector. 其余的最终将由垃圾收集器清理。 You don't need worry about this. 你不需要担心这个。

"Memory usage" as displayed by tools like Taskmgr.exe or ProcExp.exe tells you squat about the actual memory in use by a program. Taskmgr.exe或ProcExp.exe等工具显示的“内存使用情况”会告诉您蹲下程序使用的实际内存。 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. 这会削减工作集,即使用的RAM量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM