Out of memory exception in C# Eval function
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/1799373/how-can-i-prevent-compileassemblyfromsource-from-leaking-memory">How can I prevent CompileAssemblyFromSource from leaking memory?</a>  </p>
</blockquote>



<p>I am using this <a href="http://www.codeproject.com/Articles/11939/Evaluate-C-Code-Eval-Function" rel="nofollow">http://www.codeproject.com/Articles/11939/Evaluate-C-Code-Eval-Function</a> example to evaluate a c# expression which will be evaluated thousands of time.</p>

<pre><code>public static object Eval(string sCSCode) {
    CSharpCodeProvider c = new CSharpCodeProvider();
    ICodeCompiler icc = c.CreateCompiler();
    CompilerParameters cp = new CompilerParameters();

    cp.ReferencedAssemblies.Add("system.dll");
    cp.ReferencedAssemblies.Add("system.data.dll");

    StringBuilder sb = new StringBuilder("");
    sb.Append("using System;\n" );
    sb.Append("using System.Data;\n");
    sb.Append("namespace CSCodeEvaler{ \n");
    sb.Append("public class CSCodeEvaler{ \n");
    sb.Append("public object EvalCode(){\n");
    sb.Append("return "+sCSCode+"; \n");
    sb.Append("} \n");
    sb.Append("} \n");
    sb.Append("} \n");

    CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());

    if( cr.Errors.Count &gt; 0 ){
        MessageBox.Show("ERROR: " + cr.Errors[0].ErrorText, "Error evaluating cs code", MessageBoxButtons.OK, MessageBoxIcon.Error );
        return null;
    }

    System.Reflection.Assembly a = cr.CompiledAssembly;
    object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");

    Type t = o.GetType();
    MethodInfo mi = t.GetMethod("EvalCode");

    object s = mi.Invoke(o, null);
    return s;
}
</code></pre>

<p>Eval function runs almost (as mentioned above) thousands of time to do its expression evalution inside a for  each loop.
buts once the loop value reaches 4000 it gives me </p>

<pre><code>System.OutOfMemoryException occured in System.dll
</code></pre>

<p>over this line  </p>

<pre><code>CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());
</code></pre>

<p>Then it keeps giving this exception until the loop reaches to end. I created a dump file from task manager and dump file size reaches almost 500MB, I debugged the dump file using <strong>WinDbg</strong> but cant get to the problem because I am not an expert user of <strong>WinDbg</strong>  so can't figure out why its happening? I am not sure either its memory leakage problem, memory is not being freed by <code>StringBuilder</code>.</p>

<ol>
<li><p>Will Creating <code>AppDomain</code> solve the problem?</p></li>
<li><p>Shall I use <code>StringWriter</code> instead of <code>StringBuilder</code>?</p></li>
</ol>

<p>Any suggestion or help will be much appreciated.  </p>
