我使用CSharpCodeProvider编译我的代码,并在结果汇编中动态创建某个类的实例.比我叫一些方法.如果方法有递归,我得到StackOverflowException,我的应用程序终止.
我该如何避免这种情况?
using System;
using System.Runtime.Remoting;
namespace TestStackOverflow
{
class Program
{
class StackOver : MarshalByRefObject
{
public void Run()
{
Run();
}
}
static void Main(string[] args)
{
AppDomain domain = AppDomain.CreateDomain("new");
ObjectHandle handle = domain.CreateInstance(typeof (StackOver).Assembly.FullName, typeof (StackOver).FullName);
if (handle != null)
{
StackOver stack = (StackOver) handle.Unwrap();
stack.Run();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Rya*_*all 10
StackOverflow表示您的递归过深,堆栈内存不足.例如:
public class StackOver
{
public void Run()
{
Run();
}
}
Run Code Online (Sandbox Code Playgroud)
这将导致堆栈溢出,因为StackOver :: Run()将被反复调用,直到没有内存为止.
我怀疑在你的情况下,你可能会错过终止条件或者你正在运行太多的递归迭代.
如果您尝试保持应用程序运行,请尝试:
namespace TestStackOverflow
{
class Program
{
class StackOver : MarshalByRefObject
{
public bool Run()
{
return true; // Keep the application running. (Return false to quit)
}
}
static void Main(string[] args)
{
// Other code...
while (stack.Run());
}
}
}
Run Code Online (Sandbox Code Playgroud)
Run正在调用Run.那是无限递归.
class StackOver : MarshalByRefObject
{
public void Run()
{
Run(); // Recursive call with no termination
}
}
Run Code Online (Sandbox Code Playgroud)