use*_*443 7 c# console service onstart
我正在尝试将控制台应用程序转换为Windows服务.我试图让服务的onstart方法在我的类中调用一个方法,但我可以;似乎让它工作.我不确定我是否正确这样做.我在哪里将课程信息放入服务中
protected override void OnStart(string[] args)
{
EventLog.WriteEntry("my service started");
Debugger.Launch();
Program pgrm = new Program();
pgrm.Run();
}
Run Code Online (Sandbox Code Playgroud)
来自评论:
namespace MyService {
static class serviceProgram {
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main() {
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] {
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Windows服务上的MSDN文档非常好,并且具备入门所需的一切.
您遇到的问题是因为您的OnStart实现,它只应该用于设置服务以便它可以启动,该方法必须立即返回.通常,您可以在另一个线程或计时器上运行大量代码.请参阅OnStart页面以进行确认.
编辑: 不知道你的Windows服务会做什么,很难告诉你如何实现它,但是假设你想在服务运行时每隔10秒运行一次方法:
public partial class Service1 : ServiceBase
{
private System.Timers.Timer _timer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
#if DEBUG
System.Diagnostics.Debugger.Launch(); // This will automatically prompt to attach the debugger if you are in Debug configuration
#endif
_timer = new System.Timers.Timer(10 * 1000); //10 seconds
_timer.Elapsed += TimerOnElapsed;
_timer.Start();
}
private void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
// Call to run off to a database or do some processing
}
protected override void OnStop()
{
_timer.Stop();
_timer.Elapsed -= TimerOnElapsed;
}
}
Run Code Online (Sandbox Code Playgroud)
这里,该OnStart方法在设置计时器后立即返回,TimerOnElapsed并将在工作线程上运行.我还添加了一个调用,System.Diagnostics.Debugger.Launch();这将使调试更容易.
如果您有其他要求,请编辑您的问题或发表评论.