我正在學習創建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