C# 内存泄漏?

标签 c# regex memory-leaks

以下代码由于内存使用率过高而在一段时间后崩溃(我打开 taskmanager 并且其使用的内存不断增加)。但是我看不到任何内存泄漏,除了垃圾收集没有完成它的工作。有什么建议吗?

//Load a list of regex
//Load a list of phrases
//Open a output file

foreach (string regexString in regexList)
{
    int num = 0;

    Regex regex = new Regex(regexString, RegexOptions.Compiled | RegexOptions.IgnoreCase);

    foreach (string phrase in phraseList)
            num += regex.Matches(phrase).Count;

    if (num > 0)
    {
        output.WriteLine(String.Join(" ", num, phrase));
        output.Flush();
    }
}

编辑:

完整代码:http://pastebin.com/0SQYn44z

编辑2:

我找到并发布了解决方案(foreach 循环) 感谢所有试图提供帮助的人。

最佳答案

我无法从您的示例中看出,但有可能是 RegexOptions.Compiled 标志导致了问题。来自 msdn:

Compiled specifies that the regular expression is compiled to an assembly. This yields faster execution but increases startup time. This value should not be assigned to the Options property when calling the CompileToAssembly method.

如果将正则表达式编译为程序集,则在您重新启动应用程序之前无法卸载生成的代码,因为 .Net 不会卸载程序集。

这意味着如果您有很多不同的正则表达式,并且您不重用它们,那么编译的正则表达式通常不是一个好主意。

关于C# 内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11174366/

相关文章:

c++ - 解析 std::string 以选择字符

xcode - 永远不会读取在其初始化期间存储的值

iphone - 内存攀升,但代码中没有任何内存泄漏,发生在 iPhone 3G、SDK 3.0 中

Delphi:使用 [weak] 属性的对象聚合和内存泄漏

c# - “Column count doesn' t 第 1 行的匹配值计数”

c# - 从相册中获取照片 Facebook C#sdk

c# - 是否有可用的纯 C# ZeroConf 、 bonjour 或 dns-sd ?

c# - C# 中的 WebBrowsing - 库、工具等 - 是否类似于 Perl 中的 Mechanize?

Python 查找重复项并保留注释字符串

.net - .NET能保证正则表达式匹配的顺序吗?