简体   繁体   中英

Process is terminated due to StackOverflowException

This is difficult situation to explain. Have a service process that starts 2 threads, each thread loops forever but sleeps for 5 minutes each once the payload is finished.

Problem is that my second thread terminates well before the payload is even finished, for no apparent reason, and i also can't catch the exception as it seems to be triggered from outside the delegate process?

Any suggestions on how to find the problem?

The code....

public void StartService()
{
  ThreadStart stRecieve = new ThreadStart(DownloadNewMail);
  ThreadStart stSend = new ThreadStart(SendNewMail);
  senderThread = new Thread(stRecieve);
  recieverThread = new Thread(stSend);

  sendStarted = true;
  recieveStarted = true;

  senderThread.Start();
  recieverThread.Start();
}

private void DownloadNewMail()
{
  while(recieveStarted)
  {
    //Payload....

    if (recieveStarted)
    {
      Thread.Sleep(new TimeSpan(0, confSettings.PollInterval, 0));
    }
  }
}

private void SendNewMail()
{
  while(sendStarted)
  {
    //Payload....

    if (sendStarted)
    {
      Thread.Sleep(new TimeSpan(0, confSettings.PollInterval, 0));
    }
  }

}

Try to check callstack lenght in your code:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Hop();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception - {0}", e);
        }
    }

    static void Hop()
    {
        CheckStackTrace();
        Hip();
    }

    static void Hip()
    {
        CheckStackTrace();
        Hop();
    }

    static void CheckStackTrace()
    {
        StackTrace s = new StackTrace();
        if (s.FrameCount > 50)
            throw new Exception("Big stack!!!!");
    }
}

If you are having trouble following the flow of your application's code execution, try logging the entrance of methods with a timestamp and threadid.

Also, You can't catch the exception because it is a StackOverflowException.

See msdn: "Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. Consequently, users are advised to write their code to detect and prevent a stack overflow. For example, if your application depends on recursion, use a counter or a state condition to terminate the recursive loop. "

Do you utlize any heavy-weight library for tasks like DownloadNewMail and SendNewMail? For example I encountered StackOverflows when running large jobs using Microsoft.SqlServer.Dts.Runtime.Package. Try running the same workload sequentially inside a command-line application to see if the issue persists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM