【发布时间】:2023-03-23 21:01:01
【问题描述】:
我用 C# 编写了一个 Windows 服务,它基本上每分钟检查我的数据库中的订单,从这些订单生成 PDF,然后通过电子邮件发送。
逻辑在我的测试等中完美运行。
当我创建服务并使用安装项目安装它时,当我在服务 mmc 中启动服务时,我得到:
error 1053 服务没有及时响应启动或控制请求
我的 OnStart 方法如下所示:
protected override void OnStart(string[] args)
{
//writeToWindowsEventLog("Service started", EventLogEntryType.Information);
timer.Enabled = true;
}
基本上,只需启用计时器......所以那里没有进程密集型调用。
我哪里出错了?
我已经尝试将启动帐户设置为本地系统、网络服务等...没有任何效果!
编辑:
这是我的代码:(processPurchaseOrders 是查询 db 并生成 pdf 等的方法...)
public partial class PurchaseOrderDispatcher : ServiceBase
{
//this is the main timer of the service
private System.Timers.Timer timer;
public PurchaseOrderDispatcher()
{
InitializeComponent();
}
// The main entry point for the process
static void Main()
{
#if (!DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new PurchaseOrderDispatcher() };
ServiceBase.Run(ServicesToRun);
#else //debug code
PurchaseOrderDispatcher service = new PurchaseOrderDispatcher();
service.processPurchaseOrders();
#endif
}
private void InitializeComponent()
{
this.CanPauseAndContinue = true;
this.ServiceName = "Crocus_PurchaseOrderGenerator";
}
private void InitTimer()
{
timer = new System.Timers.Timer();
//wire up the timer event
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
//set timer interval
var timeInSeconds = Convert.ToInt32(ConfigurationManager.AppSettings["TimerIntervalInSeconds"]);
timer.Interval = (timeInSeconds * 1000); // timer.Interval is in milliseconds, so times above by 1000
timer.Enabled = true;
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
components.Dispose();
base.Dispose(disposing);
}
protected override void OnStart(string[] args)
{
//instantiate timer
Thread t = new Thread(new ThreadStart(this.InitTimer));
t.Start();
}
protected override void OnStop()
{
//turn off the timer.
timer.Enabled = false;
}
protected override void OnPause()
{
timer.Enabled = false;
base.OnPause();
}
protected override void OnContinue()
{
timer.Enabled = true;
base.OnContinue();
}
protected void timer_Elapsed(object sender, ElapsedEventArgs e)
{
processPurchaseOrders();
}
}
【问题讨论】:
-
你的构造函数中有什么?问题可能就在那里。
-
我的构造函数中只有 this.CanPauseAndContinue = true; this.ServiceName = "Crocus_PurchaseOrderGenerator";
-
你在哪里实例化计时器?看看我在下面发布的示例 (clifgriffin.com/2008/11/20/using-timers-in-a-c-windows-service),了解如何在 Windows 服务中设置计时器
-
我编辑了问题并添加了所有代码......
-
我使用您的大部分代码通过一个完整的示例更新了我的答案。它开始正常,我能够附加并看到事件正在触发。
标签: c# windows error-handling windows-services