c# 超时时间已到.在操作完成之前超时时间已过或服务器未响应,Visual Studio C#:该服务没有及时响应启动或控制请求...

博主在开发一个服务时遇到问题,服务启动时频繁报错,尽管调试正常。服务启动后会立即进入OnTimer方法,导致状态误判为运行。尝试调整超时时间和手动状态更新均无效。寻求帮助解决定时器触发服务状态更新的时机问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我创建了一个服务,该服务对一个数据库执行多次检查,并使用检查结果更新另一个数据库。 但是,每次尝试启动服务时都会出现主题错误。 我能够在调试器中成功运行该服务,并且一切正常。 我也调整了这里描述的超时时间http://support.microsoft.com/kb/824344无济于事。 下面是我的Program.cs文件:Visual Studio C#:该服务没有及时响应启动或控制请求

namespace PlantMonitor

{

static class Program

{

///

/// The main entry point for the application.

///

static void Main()

{

#if (!DEBUG)

ServiceBase[] ServicesToRun;

ServicesToRun = new ServiceBase[]

{

new Service1()

};

ServiceBase.Run(ServicesToRun);

#else

var service = new Service1();

service.StartUp(); //Make the method public in order to Debug

System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

#endif

}

}

}

,这里是我的Service1.cs文件:

namespace PlantMonitor

{

public partial class Service1 : ServiceBase

{

//declare the SetServiceStatus function by using platform invoke

[DllImport("advapi32.dll", SetLastError = true)]

.

.

.

public void StartUp()

{

OnStart(null);

}

protected override void OnStart(string[] args)

{

//startup stuff

// Update the service state to Start Pending.

ServiceStatus serviceStatus = new ServiceStatus();

serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;

serviceStatus.dwWaitHint = 180000;

SetServiceStatus(this.ServiceHandle, ref serviceStatus);

//ConnectionState

eventLog1.WriteEntry("In OnStart");

// Set up a timer to trigger every minute.

timer.Interval = 10000; // 10 seconds

timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);

timer.Start();

//Confrim Timer success

eventLog1.WriteEntry("Timer Success");

// Update the service state to Running.

serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;

SetServiceStatus(this.ServiceHandle, ref serviceStatus);

}

基本上,我设置定时器为10秒最初开始主的第一次迭代包含在OnTimer中的代码,并调整计时器。一旦我进入OnTimer内部,间隔为3分钟。 当我尝试启动该服务时,我可以看到它将事件报告给OnTimer方法中存在的日志文件。

这是我在写一个服务的第一次尝试,但我没有料想到会被认为是服务“运行”,一旦它击中这行代码:当我在调试器中运行

// Update the service state to Running.

serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;

SetServiceStatus(this.ServiceHandle, ref serviceStatus);

,它在触发OnTimer之前总是到达这一行代码。我没有正确更新服务状态吗?

[编辑]回顾事件日志后,即使在服务管理器抛出主题错误后,服务仍然继续运行OnTimer事件。但是,一旦完成一次OnTimer方法,服务就会停止。

+0

您不需要手动对服务状态执行任何操作。 'ServiceBase.Run'应该为你处理所有的事情。 –

2014-09-03 12:56:52

+0

我删除了手动服务状态更新并在Main方法中调用ServiceBase.Run,​​但这不能解决问题。 public static void Main() {System.ServiceProcess.ServiceBase.Run(new Service1()); }' –

2014-09-03 13:19:08

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值