Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Memory Leak?

The following code crashes after sometime due to high memory usage (I open taskmanager and its used memory keeps raising). But I cant see any memory leak except for garbage collection not doing its job. Any suggestions?

//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();
    }
}

EDIT:

Complete Code: http://pastebin.com/0SQYn44z

EDIT2:

I found and posted the solution (foreach loop) Thanks for everyone that tried to help in anyway.

like image 968
David Benko Avatar asked Dec 20 '22 20:12

David Benko


1 Answers

I can't tell from your example, but it is possible that the RegexOptions.Compiled flag causes the problem. From 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.

If a regex is compiled to an assembly, then the generated code can not be unloaded until you restart the application as .Net does not unload assemblies.

This means that if you have a lot of different regular expressions, and you don't reuse them, a compiled Regex is usualy not a good idea.

like image 111
Elian Ebbing Avatar answered Dec 29 '22 01:12

Elian Ebbing