Possible Duplicate:
How can I prevent CompileAssemblyFromSource from leaking memory?
I am using this http://www.codeproject.com/Articles/11939/Evaluate-C-Code-Eval-Function example to evaluate a c# expression which will be evaluated thousands of time.
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 > 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;
}
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
System.OutOfMemoryException occured in System.dll
over this line
CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());
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 WinDbg but cant get to the problem because I am not an expert user of WinDbg so can't figure out why its happening? I am not sure either its memory leakage problem, memory is not being freed by StringBuilder.
Will Creating
AppDomainsolve the problem?Shall I use
StringWriterinstead ofStringBuilder?
Any suggestion or help will be much appreciated.