c# - 如何在 Windows 服务中运行长时间运行的进程?

标签 c# windows-services

谁能告诉我如何从 Windows 服务(在 C# 中)运行长时间运行的进程?该过程可能需要数小时才能完成。该服务应检查数据库中是否有待执行的作业。每项工作可能需要很长时间才能完成。如果没有挂起的作业,那么它应该休眠 2 分钟(可配置),然后重新开始。我如何使用 Windows 服务执行此操作?提前致谢。

最佳答案

你必须像这样创建控制台应用程序

    static void Main(string[] args)

    {
       bool createdNew;
        Mutex m = new Mutex(true, "YourBatchProcessor", out createdNew);
        if (!createdNew)
        {
             Console.WriteLine("YourBatchProcesso is already running!");
            return;
        }
        //your code goes here

    }

正如 Gmoliv 所说,创建计划任务而不是每 2 分钟运行一次

或者如果你想写窗口服务那么你的服务代码就像

   public class YourServrClass
   {

    private int numticks = 0;
    private Timer _timer;
    private bool _IsStarted;
    private int Interval =2000; //ticks //2 sec.
    #region Initializer
     public YourServrClass()
    {
        InitializeComponent();
        _timer = new Timer();
         _timer.Interval = Interval;
        _timer.Elapsed += new ElapsedEventHandler(this.Timer_Tick);
    }
    #endregion

    #region Timer_Tick to process

    private void Timer_Tick(object sender, System.Timers.ElapsedEventArgs e)
    {
        numticks++;
        if (_IsStarted)
        {
            _timer.Stop();

            //your code //ProcessYourData();
            _timer.Start();
        }
    }
    #endregion
    protected override void OnStart(string[] args) 
    { 
           _IsStarted=true;
    } 

    protected override void OnStop() 
    { 
          _IsStarted=false;
    } 

 }

关于c# - 如何在 Windows 服务中运行长时间运行的进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3891684/

相关文章:

c# - 流式下载的 WCF 最佳实践/配置

c# - 如何延迟关闭并在窗口服务中运行进程

c# - 如何允许用户编辑 Program Files 下的 App.config 是记事本或其他编辑器?

c# - 系统启动/重新启动时 WMI 调用花费太多时间

c# - Windows 服务在测试时有效但不作为服务

C#,html-agility-pack 获取不在标签内的文本

c# - 无法在 WPF 的 DataTemplate 中为 TextBox 设置前景

c# - 如何在.NET中以编程方式测量当前进程的总内存消耗?

c# - 在多用户 Web 环境中生成顺序发票编号

c# - 将一个二维数组复制到另一个二维数组