我正在学习创建Windows服务和线程。我正在使用由同事提供的图书馆,它帮助建立线程服务,但这并没有给我基本的知识。假设我将有一个长期运行的服务(比网上提供的基本示例稍微提前一些),需要每15秒唤醒一次,然后执行其操作(基本上将始终运行)。行动包括在数据库中查找状态,然后执行操作。Windows服务和计时器
应该如何以下在这样的情况下进行处理:
1.设置所述螺纹
2.情况下动作时间比间隔执行。
我发现了下面的例子,但我有上述2点的问题。请记住,该服务将始终运行。
http://www.java2s.com/Tutorial/CSharp/0280__Development/CreatethedelegatethattheTimerwillcall.htm
using System;
using System.Threading;
class MainClass
{
public static void CheckTime(Object state)
{
Console.WriteLine(DateTime.Now);
}
public static void Main()
{
TimerCallback tc = new TimerCallback(CheckTime);
Timer t = new Timer(tc, null, 1000, 500);
Console.WriteLine("Press Enter to exit");
int i = Console.Read();
// clean up the resources
t.Dispose();
t = null;
}
}
所以在我的例子,你会在
1.停止事件
2.去是否启动事件看起来不错?
3.如果在队列中没有发现什么应该发生?
4.如果动作花费的时间比间隔更长,会怎么样?
public partial class QueueService : ServiceBase
{
public QueueService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
TimerCallback tc = new TimerCallback(CheckQueue);
Timer t = new Timer(tc, null, 10000, 15000); //first time wait for 10seconds and then execte every 15seconds
}
catch (Exception ex)
{
what should i be checking here and then also make sure that the threading/timer doesn't stop. It should still execute every 15 seconds
}
}
protected override void OnStop()
{
what needs to go here...
}
private static void CheckQueue(Object state)
{
... Connect to the DB
... Check status
... if queue status found then perform actions
. A
. C
. T
. I
. O
. N
. S
... if end
}
}
感谢您的期待!
很抱歉的坏格式。不知何故无法正确完成它。 – 2012-08-13 07:24:06
谢谢你,这真的让我很清楚。 我也在研究和发现以下2个资源。这些也帮助: http://www.codeguru.com/csharp/.net/cpp_managed/windowsservices/article.php/c6919/Using-Timers-in-a-Windows-Service.htm http:// csharpstruggles。 blogspot.ca/2005/02/using-timer-in-windows-service.html 不要担心格式。我已经明白了。 – 2012-08-13 07:45:20
还有一个问题刚刚出现在我的脑海里...... 如果我把CheckQueue工人放在一个单独的类中,在这种情况下,我该如何处理timer.change?我应该在这里保持checkqueue,然后在这里调用另一个类的方法吗? – 2012-08-13 07:57:01