c# - 进程因 StackOverflowException 而终止

标签 c# multithreading windows-services

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

问题是我的第二个线程甚至在有效负载完成之前就终止了,原因不明,而且我也无法捕获异常,因为它似乎是从委托(delegate)进程外部触发的?

关于如何找到问题有什么建议吗?

代码....

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

最佳答案

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

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

关于c# - 进程因 StackOverflowException 而终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4449259/

相关文章:

c# - 我如何在字符串变量中运行 ASM 操作码或将其转换为字节?

multithreading - 负载下降后线程会缠绕

c# - 在 Windows 服务中使用的最佳计时器

c# - 是否可以运行托管在 Windows 服务中的 Orleans

c# - 我们应该在 C# 中使用 String.format 还是 String.replace?

c# - IIS 花费大量时间来交付第一个 javascript 和图像文件

c# - 如何取消任务但等到它完成?

c# - 从 .NET 3.5 中的单独线程设置 Form.Owner

multithreading - MonoTouch 6.x 中的线程模型更改?

c# - Quartz.net 调度程序内存泄漏