C#线程没有释放内存 [英] C# Thread not releasing memory

查看:781
本文介绍了C#线程没有释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写在C#.NET Windows服务。当服务启动时,我产生一个新的线程,如下图所示。

I have a windows service written in C#.Net. When the service is started, I spawn a new thread as shown below

new Thread(new ThreadStart(Function1)).Start();

这线程无限循环,并预计执行我的服务的职责。每天一次,我需要同时执行不同的操作而我的线程派生低于

This thread loops infinitely and performs the duties expected of my service. Once a day, I need to simultaneously perform a different operation for which my thread spawns a second thread as show below

new Thread(new ThreadStart(Function2)).Start(); 

这第二个线程执行一个很简单的功能。它读取使用FileReadAllLines一个文本文件中的所有行,迅速​​处理这些信息并退出。

This second thread performs a very simple function. It reads all the lines of a text file using FileReadAllLines , quickly processes this information and exits.

我的问题是,第二个线程它读取文件中使用的内存没有得到收集。我让我的服务运行3小时,希望这个GC会被调用,但什么都没有发生和任务管理器仍显示我的服务使用的内存150MB。读取和处理文本文件的功能是一个非常简单的,我相信有包含文本字符串数组没有隐藏引用。可能有人解释为什么这种情况正在发生一些轻?难道是有可能被另一个催生了一个线程催生线程后本身不清理?

My problem is that the memory used by the second thread which reads the file is not getting collected. I let my service run for 3 hours hoping that the GC would be called but nothing happened and task manager still shows that my service is using 150mb of memory. The function to read and process the text file is a very simple one and I am sure there are no hidden references to the string array containing the text. Could someone shed some light on why this is happening? Could it be possible that a thread spawned by another spawned thread cannot cleanup after itself?

感谢

推荐答案

如果您正在使用Windows任务管理器来尝试了使用的内存,它很可能是欺骗你。由CLR使用的内存通常不返回到操作系统,据我所知......所以你可能仍然看到较高的工作集,尽管大多数内存是那么仍然可以被重复使用内流程。

If you're using Windows task manager to try to work out the memory used, it's likely to be deceiving you. Memory used by the CLR isn't generally returned to the operating system as far as I'm aware... so you'll potentially still see a high working set, even though most of that memory is then still available to be reused within the process.

如果你让服务运行了一个星期,你看到的内存使用量节节高攀通过一周,或者它只是在第一天增加,然后高原?如果是这样,你肯定认为这是一个问题吗?如果是这样,你可能需要把你的第二个任务中的一个单独的进程。

If you let the service run for a week, do you see the memory usage climb steadily through the week, or does it just increase in the first day, and then plateau? If so, do you definitely view this as a problem? If so, you may need to put your second task in a separate process.

这篇关于C#线程没有释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆