我在这里使用窗口服务,使用一个逻辑,因为在 app.config 中配置的帮助下,我的服务将在 24 小时内只工作一次。
例如:我会在应用程序配置中提到小时为“10”,所以每天一次我的服务将正好运行 10 点
但问题是当我启动我的服务时,它抛出一个错误 1053(及时时尚错误)并且状态显示为 Starting in services.msc,没有更多的启动和重新启动功能未显示在弹出窗口中右键单击
想知道它是否完美地完成了工作,正好在十点之前。
为什么它没有显示为已启动,为什么会抛出错误?
我已将示例代码粘贴到下面,如果我做错了,请多多指教
启动方式
protected override void OnStart(string[] args)
{
DateTime tenAM = DateTime.Today.AddHours(strSETHOST);
if (DateTime.Now > tenAM)
tenAM = tenAM.AddDays(1);
// calculate milliseconds until the next 10:00 AM.
int timeToFirstExecution = (int)tenAM.Subtract(DateTime.Now).TotalMilliseconds;
// calculate the number of milliseconds in 24 hours.
int timeBetweenCalls = (int)new TimeSpan(24, 0, 0).TotalMilliseconds;
TimerCallback methodToExecute = kickstart;
// start the timer. The timer will execute "ProcessFile" when the number of seconds between now and
// the next 10:00 AM elapse. After that, it will execute every 24 hours.
System.Threading.Timer timer = new System.Threading.Timer(methodToExecute, null, timeToFirstExecution, timeBetweenCalls);
Thread.Sleep(Timeout.Infinite);
}
protected override void OnStop()
{
}
public static void kickstart(object nowtime)
{
Service1 foo = new Service1();
foo.Startjob();
}
private void Startjob()
{
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew)) // Transaction Scope Started
{
if ((threadPURGE == null) || (threadPURGE.ThreadState == System.Threading.ThreadState.Stopped) || (threadPURGE.ThreadState == System.Threading.ThreadState.Unstarted) || (threadPURGE.ThreadState == System.Threading.ThreadState.Aborted))
{
threadPURGE = new Thread(new ThreadStart(DynamicThreadGen)); // Thread Initialize for ITD
}
try
{
if ((threadPURGE == null) || (threadPURGE.ThreadState == System.Threading.ThreadState.Stopped) || (threadPURGE.ThreadState == System.Threading.ThreadState.Unstarted) || (threadPURGE.ThreadState == System.Threading.ThreadState.Aborted))
{
threadPURGE.Start(); // Thread Started for ITD
}
}
catch (Exception ex)
{
string err = ex.Message.ToString();
}
finally
{
scope.Complete();
}
}
}
private void DynamicThreadGen()
{
/// service work
}
请您参考如下方法:
您需要允许您的 OnStart 方法在 Windows 分配的超时时间内完成,否则 Windows 无法判断它已经启动。保留类字段中的 Timer,这样它就不会被垃圾收集和处理,然后放弃 Thread.Sleep
