如何实现在C#/ .NET2.0中等待一段时间的Windows服务循环

时间:2010-04-07 15:09:41

标签: c# windows-services

我的问题是,这是执行此操作的最佳做​​法。找不到任何好的例子。我在VS2005创建的文件中有以下代码:

public partial class ObjectFolder : ServiceBase
{
    protected override void OnStart(string[] args)
    {
        ObjectFolderApp.Initialize();

        ObjectFolderApp.StartMonitorAndWork();
    }

    protected override void OnStop()
    {
        // TODO: Add code here to perform any tear-down necessary to stop yourservice.
    } 
}

然后:

class ObjectFolderApp
{
    public static bool Initialize()
    {
        //all init stuff
        return true;
    }


    public static void StartMonitorAndWork()
    {
        Thread worker = new Thread(MonitorAndWork);
        worker.Start();
    }


    private static void MonitorAndWork()
    {
        int loopTime = 60000;
        if (int.TryParse(_cfgValues.GetConfigValue("OfWaitLoop"), out loopTime))
            loopTime = 1000 * loopTime;

        while (true)
        {
            /* create+open connection and fill DataSet */
            DataSet ofDataSet = new DataSet("ObjectFolderSet");
            using (_cnctn = _dbFactory.CreateConnection())
            {
                _cnctn.Open();

                //do all kinds of database stuff
            }
            Thread.Sleep(loopTime);
        }
    }
}

2 个答案:

答案 0 :(得分:14)

this question重新哈希我的答案,推荐的方法是使用计时器和以下代码:

public class MyService : ServiceBase
{
    private Timer workTimer;    // System.Threading.Timer

    protected override void OnStart(string[] args)
    {
        workTimer = new Timer(new TimerCallback(DoWork), null, 5000, 5000);
        base.OnStart(args);
    }

    protected override void OnStop()
    {
        workTimer.Dispose();
        base.OnStop();
    }

    private void DoWork(object state)
    {
        RunScheduledTasks();  // Do some work
    }
}

简单!

请注意,所使用的Timer类型为System.Threading.Timer,与Justin指定的类型相同。

答案 1 :(得分:3)

使用System.Threading.Timer以预定的时间间隔关闭此过程。