【发布时间】:2026-02-20 04:20:02
【问题描述】:
我有两个问题:
-
我正在创建一个 Windows 服务,它将在每天凌晨 3 点 GMT 将数据库导出到一台服务器上并导入到另一台服务器上。我已经安装了我的服务并遵循了这个:https://msdn.microsoft.com/en-us/library/sd8zc8ha(v=vs.110).aspx。但是,我在服务代码中尝试过,它不允许我附加到该进程,并且还尝试在空白的 Visual Studio 页面中执行此操作(都作为管理员)并且不能,问题是当我运行我的服务由于某种原因停止了,所以如果可能的话,我需要一些关于如何测试和调试的想法,以确保服务正在做我想要的。
-
我正在使用我的事件查看器告诉我一些错误,但这似乎随着时间的推移而代价高昂,但是我收到了一个错误,即:
服务无法启动。 System.ArgumentException:在写入事件日志之前未设置源属性。 在 System.Diagnostics.EventLogInternal.WriteEntry(字符串消息,EventLogEntryType 类型,Int32 eventID,Int16 类别,Byte[] rawData) 在 System.Diagnostics.EventLog.WriteEntry(字符串消息) 在 C:\Dev\Projects\DBBackUpService\DBBackUpService\BackUpService.cs:line 27 中的 DBBackUpService.BackUpService.OnStart(String[] args) 在 System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(对象状态)
错误开始的代码在 OnStart 方法的开头:
System.Timers.Timer _timer = null;
bool backUpRunning = false;
public BackUpService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
BackUpLog.WriteEntry("Database Backup has begun.");
_timer = new System.Timers.Timer { Interval = 3600000 };
_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
_timer.Start();
Backup();
}
protected override void OnStop()
{
_timer.Stop();
BackUpLog.WriteEntry("Database Backup has finished.");
}
public void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
TimeSpan start = new TimeSpan(3, 0, 0);
TimeSpan end = new TimeSpan(5, 0, 0);
TimeSpan now = DateTime.Now.TimeOfDay;
BackUpLog.WriteEntry("Checking if it's time to run the archive service and checking if the service is already running");
if (backUpRunning)
BackUpLog.WriteEntry("Service is already running");
if ((now > start) && (now < end) && !backUpRunning)
{
BackUpLog.WriteEntry("Service is not already running and the time of day is valid to run the service.");
try
{
backUpRunning = true;
BackUpLog.WriteEntry("Initialising archive service");
}
catch (Exception ex)
{
logArchiveServiceError("The archive service failed. It will return to step 1 and try again: " + ex.Message);
}
finally
{
backUpRunning = false;
}
}
}
private void logArchiveServiceError(string errorMessage)
{
BackUpLog.WriteEntry(errorMessage, EventLogEntryType.Error);
//Emailer.SendErrorAlertEmail("Archive Service Error", errorMessage, null, null);
}
private void logArchiveServiceInfo(string info)
{
BackUpLog.WriteEntry(info, EventLogEntryType.Information);
}
TO ADD:创建此服务是为了将数据从一个数据库导出到另一个数据库。
【问题讨论】:
-
为什么不修复第 27 行的异常以便查看事件?
-
好吧,在我的情况下说起来容易做起来难,因为我是创建 Windows 服务的新手,我害怕所以我不知道如何解决它。
-
如果你提供你的代码会更容易帮助。
-
提供重现问题的minimal reproducible example,以便其他人可以协助确定问题并提出可能的解决方案(如果有)。
标签: c# mysql debugging testing service