堆栈溢出异常解决方法(间歇性 - 抛出前 3-4 小时)

本文关键字:小时 异常 栈溢出 解决 方法 堆栈 | 更新日期: 2023-09-27 17:55:51

对不起,编程有点新手,希望你能帮上忙。

我意识到这个异常已经被覆盖了很多,我已经做了相当多的谷歌搜索/堆栈溢出搜索来尝试找到解决方法。

我的代码似乎仅在运行超过 3-4 小时后产生异常?该程序设置为永久连续循环。我有一个PHP页面,将发布到SQL页面的数据链接到工作正常的SQL页面。

有人可以看看我的编码并为我推荐一种防止/避免堆栈溢出异常的方法吗?该程序需要循环并每隔几秒钟运行一次,以便 SQL 数据库保持最新状态。

任何帮助将不胜感激。

也对不起代码转储,不完全确定哪个部分有问题,如果不是全部! :)

using System;
using System.Diagnostics;
using System.Xml.Linq;
using System.Net;
namespace ClientApp
{
class Program
{
    static void Main(string[] args)
    {
        Console.Title = "Client";
        CheckOnline();
    }
    private static void CallCheckOnline()
    {
        CheckOnline();
    }
    private static void CheckOnline()
    {
        try
        {
            PerformanceCounter cpuCounter;
            cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";
            cpuCounter.NextValue();
            System.Threading.Thread.Sleep(1000);
            int CPUCounter = (int)cpuCounter.NextValue();
            XElement xml = new XElement("Client");
            XElement hostname = new XElement("hostname", Dns.GetHostName());
            XElement status = new XElement("status", "Online");
            XElement counter = new XElement("counter", CPUCounter.ToString() + "%");
            xml.Add(hostname);
            xml.Add(status);
            xml.Add(counter);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/receiver.php");
            request.Method = "POST";
            xml.Save(request.GetRequestStream());
            HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
            System.Threading.Thread.Sleep(4000);
        }
        catch (Exception Ex)
        {
            Console.WriteLine("General Exception Occurred");
            Console.WriteLine("Packed Message: " + Ex.Message);
            Console.Write("Call Stack: " + Ex.StackTrace);
            System.Threading.Thread.Sleep(4000);
        }
        CallCheckOnline();
    }
}

}

堆栈溢出异常解决方法(间歇性 - 抛出前 3-4 小时)

CheckOnline方法结束时,您正在调用CallCheckOnline()再次调用相同的方法(CheckOnline)。这是一个无限递归,必然会遇到StackOverflow异常。 您没有立即遇到此异常的唯一原因是使用实际例程的Thread.Sleep和可能更长的执行时间的延迟。

您似乎正在尝试定期执行操作。您应该搜索 Timers .有很多例子可以在互联网上使用它。如果此过程必须在后台连续执行,则还可以考虑创建 Windows 服务应用程序。

无休止地调用自己的方法会导致这种情况。您最好在循环内调用CheckOnline()并删除CheckOnline()对自己的调用。

试试这个:

static void Main(string[] args)
{
    Console.Title = "Client";
    while(true)
    {
        CheckOnline();
    }
}