C# .NET windows服务突然停止
大家好, 我创建了一个windows服务,它产生了三个线程。第一个线程每15秒唤醒一次,第二个线程每分钟唤醒一次。第三个线程每天唤醒一次。 我的代码如下所示:C# .NET windows服务突然停止,c#,asp.net,windows,exception,windows-services,C#,Asp.net,Windows,Exception,Windows Services,大家好, 我创建了一个windows服务,它产生了三个线程。第一个线程每15秒唤醒一次,第二个线程每分钟唤醒一次。第三个线程每天唤醒一次。 我的代码如下所示: var timer1 = new Timer(); timer1.Elapsed += ProcessTimerEvent1; timer1.Interval = 60000; timer1.Start(); var timer2 = new Timer()
var timer1 = new Timer();
timer1.Elapsed += ProcessTimerEvent1;
timer1.Interval = 60000;
timer1.Start();
var timer2 = new Timer();
timer2.Elapsed += ProcessTimerEvent2;
timer2.Interval = 15000;
timer2.Start();
var timer3 = new Timer();
timer3.Elapsed += ProcessTimerEvent3;
timer3.Interval = 86400000;
timer3.Start();
从我的事件日志中,我可以看到它在说.NET运行时2.0错误报告EVENTID:5000
我浏览了一下网络,发现上面写着无效操作异常
你们认为停止服务是否与线程有关。
另一个愚蠢的问题是,我是否每次都会产生3个新线程,或者相同的线程每15秒或1分钟出现一次。可能您的一个线程正在抛出一个未处理的异常。这将使您的进程立即停止。通过将线程内的代码包装到try-catch块中,确保在某个时刻处理线程内的任何异常(并且不要忘记正确地记录日志,以便能够发现出错的情况).这可能是由于某个事件中的代码异常造成的。您是否在某个全局(静态)对象上保留计时器的引用?。如果不是,即使它们仍在运行,它们也是垃圾收集的候选对象。CG将调用它们的析构函数,然后依次调用Dispose方法,线程将突然停止 关于secons问题;计时器使用线程池生成线程。每个处理都将从池中获取一个线程,使用它,然后释放它。在两个周期之间,它们只是等待来自系统时钟的通知 爱丽丝 您可以使用以下代码将未处理的异常处理添加到服务中:-
namespace YourNamespace
{
static class Program
{
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
HandleException(e.Exception);
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
HandleException((Exception)e.ExceptionObject);
}
static void HandleException(Exception e)
{
//Handle/Log Exception Here
}
}
}
谢谢
菲尔