将我的代码放在哪里以便它在我的服务启动后执行?
Where to put my code so that it executes after my service starts?
只是想知道将我的代码放在哪里,以便它在我的服务启动后执行。
目前我有这样的代码
namespace sendMailService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.sendMail();
}
protected override void OnStop()
{
}
private void sendMail()
{
// My actual service code
}
}
}
当我启动服务时,它不会进入 "Running" 模式,直到 this.sendMail()
完成。顺便说一句,sendMail()
函数的最后一行是 stop()
服务。因此,服务在执行 OnStart
方法时崩溃了。
我知道为什么会这样(因为代码在OnStart
)。问题是在哪里调用 sendMail()
以便服务进入 运行 模式然后执行函数。
您可以修饰您的代码来解决您的问题。
namespace sendMailService
{
public partial class Service1 : ServiceBase
{
private System.Threading.Timer IntervalTimer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
TimeSpan tsInterval = new TimeSpan(0, 0, Properties.Settings.Default.PollingFreqInSec);
IntervalTimer = new System.Threading.Timer(
new System.Threading.TimerCallback(IntervalTimer_Elapsed)
, null, tsInterval, tsInterval);
}
protected override void OnStop()
{
IntervalTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
IntervalTimer.Dispose();
IntervalTimer = null;
}
private void IntervalTimer_Elapsed(object state)
{
// Do the thing that needs doing every few minutes...
sendMail();
}
}
}
只是想知道将我的代码放在哪里,以便它在我的服务启动后执行。
目前我有这样的代码
namespace sendMailService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.sendMail();
}
protected override void OnStop()
{
}
private void sendMail()
{
// My actual service code
}
}
}
当我启动服务时,它不会进入 "Running" 模式,直到 this.sendMail()
完成。顺便说一句,sendMail()
函数的最后一行是 stop()
服务。因此,服务在执行 OnStart
方法时崩溃了。
我知道为什么会这样(因为代码在OnStart
)。问题是在哪里调用 sendMail()
以便服务进入 运行 模式然后执行函数。
您可以修饰您的代码来解决您的问题。
namespace sendMailService
{
public partial class Service1 : ServiceBase
{
private System.Threading.Timer IntervalTimer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
TimeSpan tsInterval = new TimeSpan(0, 0, Properties.Settings.Default.PollingFreqInSec);
IntervalTimer = new System.Threading.Timer(
new System.Threading.TimerCallback(IntervalTimer_Elapsed)
, null, tsInterval, tsInterval);
}
protected override void OnStop()
{
IntervalTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
IntervalTimer.Dispose();
IntervalTimer = null;
}
private void IntervalTimer_Elapsed(object state)
{
// Do the thing that needs doing every few minutes...
sendMail();
}
}
}