由于StackOverflowException,进程终止

Jan*_*ger 7 c# multithreading windows-services

这是难以解释的情况.有一个启动2个线程的服务进程,每个线程永远循环但是一旦有效负载完成就会休眠5分钟.

问题是我的第二个线程在有效负载完成之前很好地终止,没有明显的原因,而且我也无法捕获异常,因为它似乎是从委托进程外部触发的?

有关如何找到问题的任何建议?

代码....

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));
    }
  }
Run Code Online (Sandbox Code Playgroud)

}

aco*_*aum 8

尝试检查代码中的callstack lenght:

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!!!!");
    }
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*ang 6

如果您在跟踪应用程序代码执行流程时遇到问题,请尝试使用时间戳和threadid记录方法的入口.

此外,您无法捕获异常,因为它是StackOverflowException.

请参阅msdn:"从.NET Framework 2.0版开始,tryO catch块无法捕获StackOverflowException对象,默认情况下会终止相应的进程.因此,建议用户编写代码以检测并防止堆栈溢出例如,如果您的应用程序依赖于递归,请使用计数器或状态条件来终止递归循环."

  • 我记得在MSDN上看过那篇帖子并且想"哇......人们是否抓住了StackOverflowExceptions来打破递归循环?!" (4认同)

Ole*_*lin 4

您是否使用任何重量级库来执行 DownloadNewMail 和 SendNewMail 等任务?例如,我在使用 Microsoft.SqlServer.Dts.Runtime.Package 运行大型作业时遇到 StackOverflow。尝试在命令行应用程序中按顺序运行相同的工作负载,看看问题是否仍然存在。