martedì, aprile 08, 2008

IIS6 StackOverFlow

Sometimes you need to run code with extensive use of stack due to recursive algorithms. But recursion (if very deep) can be very harmful for stack. I encountered such situation, in a particular use of iTextSharp. In my case, IIS 6 (w3wp.exe) crashed with an unknow exception that seemed to be thrown from kernel32.

I spent many hours trying to understand where the problem was. Using WinDbg and AdPlus I understood that the problem came from Net managed code, and after dumping the stack, it was clear which was the method(s).

First: it's not a library bug. If I reduce the work-load (number of input pdf files) it works perfectly. Second: the same piece of code, with the same input pdf files, runs perfectly from a command-line application. So, the problem is related to the IIS "environment".

Solution: increase the stack! Ok, but how ? Simple: running the code inside a thread with a bigger stack!
On IIS6 the "default" threads are created with 256 KB of stack. I haven't found a way to change it. But, from your asp.net code you can create and run a new thread with a bigger stack.

Example code (direct run):

protected void Button1_Click(object sender, EventArgs e)
{
this.Run();
}


private void Run()

{

//... code with or calling library with high use of stack

}



Passing trought a "working" thread (with 1 MB of stack):

protected void Button1_Click(object sender, EventArgs e)
{

this.RunAsSeparatedThread();

}


private void RunAsSeparatedThread()

{

Thread t = new Thread(Run, 1 * 1024 * 1024);

t.IsBackground = true;

t.Start();

t.Join();

}

private void Run()
{

//... code with or calling library with high use of stack

}

2 commenti:

adi ha detto...

Same problem here.
I'll try your solution and will come back with the result.

adi ha detto...

Worked for me, thanks alot!