系统.Windows Service启动时出现NullReferenceException错误
本文关键字:NullReferenceException 错误 Windows Service 启动 系统 | 更新日期: 2023-09-27 18:09:48
在尝试启动Windows服务时,当状态栏几乎处于50%时突然出现以下错误:
错误1053:服务没有及时响应启动或控制请求
当我检查事件查看器时,我看到以下错误:
应用程序:EnvMonService.exe
框架版本:v4.0.30319
描述:进程因未处理的异常而终止
Exception Info: System。得到NullReferenceException
Stack: at EnvMonService.EnvMonService. tor() at EnvMonService.Program.Main()
我看不到错误来自哪里-这是我的代码:
Main ()static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new EnvMonService()
};
ServiceBase.Run(ServicesToRun);
}
构造函数public EnvMonService()
{
InitializeComponent();
}
OnStart和OnStop
protected override void OnStart(string[] args)
{
// Start a task thread polling the databse for changes and updates the ASCII file
mainTask = new Task(PollDatabase, cts.Token, TaskCreationOptions.LongRunning);
mainTask.Start();
}
protected override void OnStop()
{
// Cancel Task and wait for it to be disposed
cts.Cancel();
mainTask.Wait();
}
我的变量// Connection to database
private string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
// Newest timestamp
private Int32 latestDate;
// Log file
public LogFileWriter logFileWriter;
// Define datastructure POCO class
EnvDataModel model = new EnvDataModel();
// Instantiate a concellation token for a task
private CancellationTokenSource cts = new CancellationTokenSource();
// Instantiate a task
private Task mainTask = null;
// Define a waiting interval between each database polling
private TimeSpan WaitAfterSuccessInterval = new TimeSpan(0, 1, 0);
// Define a waiting interval if any errors happens
private TimeSpan WaitAfterErrorInterval = new TimeSpan(0, 2, 0);
在任务
中运行的代码 private void PollDatabase()
{
// New token
CancellationToken cancellation = cts.Token;
// Fencepost problem
// Setup default interval
TimeSpan interval = TimeSpan.Zero;
// Create a new logfile instance
logFileWriter = new LogFileWriter(@"C:'LogFile.txt");
// Poll database until service stops
while (!cancellation.WaitHandle.WaitOne(interval))
{
try
{
// Poll database here and assign reponse to EnvDataModel
// Update status in logfile
logFileWriter.WriteToLogFile("Database Last Polled: " + DateTime.Now + Environment.NewLine);
// Call ASCII File Parser
ParseDataToASCIIFileAsync();
// Occasionally check the cancelation state
if (cancellation.IsCancellationRequested)
{
break;
}
interval = WaitAfterSuccessInterval;
}
catch (Exception caught)
{
// Log exception
logFileWriter.WriteToLogFile(caught.Message);
// Wait a few minutes before trying again
interval = WaitAfterErrorInterval;
}
}
}
我通过以下步骤解决了我的问题:
- 在Visual Studio中,右键单击解决方案并单击
Clean Solution
- 再次右键单击您的解决方案并单击
Build Solution
- [不必选]将
bin/debug
文件夹下的所有文件拷贝到需要运行服务的目录下。服务需要在您的本地驱动器上。 - 使用Visual Studio Developer命令提示符和
installutil
安装服务