我有一个关于 Windows Service 应用程序的问题。该应用程序有一个定时器,在每 x 秒执行一次函数。
在本地开发者 PC 上测试应用程序时,服务能正常工作。
但是,在 Windows Server 2008 上测试服务,同时编译为 Release 模式时,当我启动服务时,会出现以下错误信息:
在本地开发者 PC 上测试应用程序时,服务能正常工作。
但是,在 Windows Server 2008 上测试服务,同时编译为 Release 模式时,当我启动服务时,会出现以下错误信息:
如果我查看服务器事件查看器,会得到以下信息: 下面是我的代码片段。Error 1053: The service did not respond to the start or control request in a timely fashion
private const int TICK_TIMER = 120000; //Start timer every 2 minutes
private Timer readTimer = null;
public BarcodeReader()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
readTimer = new Timer();
readTimer.Interval = TICK_TIMER;
readTimer.Elapsed += readTimer_Tick;
readTimer.Enabled = true;
WriteLog("Servizio Barcode started");
}
private void readTimer_Tick(object sender, ElapsedEventArgs e)
{
//Start function
try
{
MyFunction();
}
catch (Exception ex)
{
WriteLog("ERROR: " + ex.Message);
}
}
private void WriteLog(string mex)
{
try
{
//sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
using (var sw = new StreamWriter(Globals.LogPath + "LogBarcodeService.txt", true))
{
sw.WriteLine(DateTime.Now.ToString(CultureInfo.CurrentCulture) + ": " + mex);
sw.Flush();
sw.Close();
}
}
catch (Exception)
{
throw;
}
}
protected override void OnStop()
{
readTimer.Enabled = false;
WriteLog("Servizio Barcode terminated");
}
注意:服务器上安装了.NET Framework 4.5,与开发者PC相同。
更新
这是对InitializeComponent
函数的调用。
namespace BarcodeReaderService
{
partial class BarcodeReader
{
/// <summary>
/// Variabile di progettazione necessaria.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Pulire le risorse in uso.
/// </summary>
/// <param name="disposing">ha valore true se le risorse gestite devono essere eliminate, false in caso contrario.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Codice generato da Progettazione componenti
/// <summary>
/// Metodo necessario per il supporto della finestra di progettazione. Non modificare
/// il contenuto del metodo con l'editor di codice.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
#endregion
}
}
更新2
我尝试将所有代码放入一个应用程序控制台,并在服务器上顺利运行它们。