Windows Service OnStart()问题 [英] Windows Service OnStart() problem

查看:112
本文介绍了Windows Service OnStart()问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我的WindowsService出现问题.
我从Codeproject中提取了示例程序,并添加了我的代码:
在C#中创建基本Windows服务 [ ^ ]

我还创建了另一个类,用于将数据写入SQL Server.
但这应该只在特定时间发生,因此我创建了一个Timer来每秒读取系统时间.

现在,我想使用服务的OnStart功能启动计时器,但是当我启动服务时,出现此错误:

在本地计算机"上启动了服务"AS400重复",然后停止了.如果某些服务未被其他服务或程序使用,则会自动停止.
(德语翻译)

Hi Guys,

I have problem with my WindowsService.
I took the example program from Codeproject and added my Code:
Creating a Basic Windows Service in C#[^]

I also created another class, with which I write data to my SQL Server.
But this should happen only at a particular time, so I created a Timer to read every second the system time.

Now I want to start the Timer with the OnStart Function of my Service, but when I start the Service this error appears:

Service "AS400 duplicate" was started on "Local Computer" and then stopped. Some services stop automatically if they are not used by other services or programs.
(translated from german)

protected override void OnStart(string[] args)
{
AS400duplicate ASdb = new AS400duplicate(); //initialise class
ASdb.StartTimer(); //start Timer
}



希望你能帮帮我!

最好的问候
Tom



I hope you can help me!

Best regards
Tom

推荐答案

之所以失败,是因为您在OnStart方法的范围内创建了AS400dupicate对象.当OnStart返回时,该对象不再在作用域中并被销毁,从而破坏了计时器.

在OnStart方法之外声明AS400duplicate变量...

顺便说一句,AS400duplicate是一个糟糕的类名.
It fails because you created the AS400dupicate object in the scope of the OnStart method. When OnStart returns, the object is no longer in scope and is destroyed, therby destroying your timer.

Declare the AS400duplicate variable outside the OnStart method...

By the way, AS400duplicate is a terrible class name.


我找到了解决方案!

我只需要像这样初始化Timer:

//计时器
公共无效的startTimer()
{
计时器timer1 = new Timer();
timer1.Elapsed + =新的ElapsedEventHandler(timer1_Elapsed);
timer1.Interval = 1000;
timer1.Enabled = true;
timer1.Start();
}

现在可以调用函数...
I found the solution!

I only had to intialize the Timer like this:

//Timer
public void startTimer()
{
Timer timer1 = new Timer();
timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
timer1.Interval = 1000;
timer1.Enabled = true;
timer1.Start();
}

Now it is possible to call the function...


这篇关于Windows Service OnStart()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆