1

我正在学习创建 Windows 服务和线程。我正在使用同事提供的帮助构建线程服务的库,但这并没有给我基本的知识。

可以说我将有一个长时间运行的服务(比网络上可用的基本示例稍有进步),需要每 15 秒唤醒一次,然后执行其操作(基本上将始终运行)。操作涉及在数据库中查找状态,然后执行操作。

在这种情况下应如何处理:
1. 处置线程
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

    }

    }

感谢您的关注!

4

1 回答 1

1
  1. 处理定时器。
  2. 不完全的。您需要在类级别声明计时器,否则它将在几次迭代后被收集。
  3. 没有什么。
  4. 在检查队列之前停止计时器,并在完成后重新启动它。这样您就不会遇到共享内存或其他冲突的麻烦。

    公共部分类 QueueService : ServiceBase {

    定时器定时器;

     public QueueService()
     {
         InitializeComponent();
     }
    
     protected override void OnStart(string[] args)
     {
        try
        {
           TimerCallback tc = new TimerCallback(CheckQueue);
    
           timer = new Timer(tc, null, 10000, 15000);
        }
        catch (Exception ex)
        {
    
        }
    }
    
    protected override void OnStop()
    {
        if (timer != null)
            timer.Dispose();
    }
    
    private static void CheckQueue(Object state) 
    {
        timer.Change(Timeout.Infinite, 0);
    
        ... Connect to the DB
        ... Check status
        ... if queue status found then perform actions
        . A
        . C
        . T
        . I
        . O
        . N
        . S
        ... if end
    
        timer.Change(10000, 15000);
    
    }
    

    }

于 2012-08-13T07:15:46.567 回答