最佳使用 Windows 服务重复程序调用 [英] Best use of Windows Service for repeating a program call

查看:22
本文介绍了最佳使用 Windows 服务重复程序调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建我的第一个 Windows 服务.这是一个连接到邮箱并下载所有邮件并将它们存储在我的本地驱动器上的组件.

Im building my first Windows Service. It's a component that connects to a mailbox and downloads all mails and store them on my local drive.

我的问题是这些.

  1. 在 c# windows 服务中重复程序调用的最佳方法是什么.我正在考虑使用一个简单的计时器?我在哪里开始和停止计时器?是服务本身还是我的服务正在运行的程序?

  1. What is the best way to repeat a program call in c# windows service. Im thinking of using a simple timer? Where do I start and stop the timer? is it in the service itself or the program my service is running?

以下功能的 Windows 服务应包含哪些代码

What code should be included in a Windows Service for the following function

<小时>

protected override void OnStart(string[] args)
{
//timer?
// MyProgram mp = new MyProgram();
}

<小时>

我是应该简单地用一个像上面那样的新实例来启动我的应用程序,还是应该包含更多的东西?


Should I simply start my application with a new instance like above or should I include more stuff?

正如我所说,这是我第一次使用 Windows 服务.

As I said this is my first time for using Windows Services so.


感谢所有的答案.当然有很多不同的方法可以做到这一点,但我发现对我来说最好的方法是将一个标记作为解决方案.


Thanks for all the answers. There are of course lots of different ways to do this but I found that best way for me is the one mark as a solution.

感谢您的帮助!

推荐答案

这是一个模板,您可以使用它来处理使用计时器的重入问题.

Here's a template you can use it handles the reentrantcy problems with using a timer.

public partial class Service : ServiceBase{

    System.Timers.Timer timer;


 public Service()
    {

    timer = new System.Timers.Timer();
    //When autoreset is True there are reentrancy problme 
    timer.AutoReset = false;


    timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
}

 protected override void OnStart(string[] args)
 {

     timer.Interval = 1;
     timer.Start();

    }

 private void DoStuff(object sender, System.Timers.ElapsedEventArgs e)
 {

    Collection stuff = GetData();
    LastChecked = DateTime.Now;

    foreach (Object item in stuff)
    {
          item.Dosomthing(); //Do somthing should only be called once
     }     


    TimeSpan ts = DateTime.Now.Subtract(LastChecked);
    TimeSpan MaxWaitTime = TimeSpan.FromMinutes(5);


    if (MaxWaitTime.Subtract(ts).CompareTo(TimeSpan.Zero) > -1)
        timer.Interval = MaxWaitTime.Subtract(ts).Milliseconds;
    else
        timer.Interval = 1;

    timer.Start();





 }

OnContinue OnPause 和 OnStop 非常容易解决.

OnContinue OnPause and OnStop are petty easy to work out.

    protected override void OnPause()
    {

        base.OnPause();
        this.timer.Stop();



    }

    protected override void OnContinue()
    {
        base.OnContinue();
        this.timer.Interval = 1;
        this.timer.Start();

    }

    protected override void OnStop()
    {
        base.OnStop();
        this.timer.Stop();
    }

这篇关于最佳使用 Windows 服务重复程序调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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