由于StackOverflowException,进程终止

时间:2010-12-15 11:10:07

标签: 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));
    }
  }

}

3 个答案:

答案 0 :(得分:8)

尝试检查代码中的调用堆栈长度:

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!!!!");
    }
}

答案 1 :(得分:6)

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

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

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

答案 2 :(得分:4)

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

相关问题