csharp 定期从Topshelf Windows服务调用多个处理程序(使用System.Threading.Timer)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 定期从Topshelf Windows服务调用多个处理程序(使用System.Threading.Timer)相关的知识,希望对你有一定的参考价值。

using System;
using System.Collections.Generic;
using System.Threading;
using Topshelf;

namespace ConsoleApplication
{
    public interface IProcess
    {
        void Perform();
    }

    public class Process1 : IProcess
    {
        public void Perform()
        {
            Console.WriteLine("Process1");
        }
    }

    public class Process2 : IProcess
    {
        public void Perform()
        {
            Console.WriteLine("Process2");
        }
    }

    public class ProcessRunner
    {
        public ProcessRunner(IEnumerable<IProcess> processes, CancellationToken ct)
        {
            _processes = processes;
            _cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
        }

        public void Start()
        {
            _timer = new Timer((x =>
            {
                foreach (var process in _processes)
                {
                    process.Perform();
                }
                
                _timer.Change(500, Timeout.Infinite);
            }), null, 0, Timeout.Infinite);
            _cts.Token.Register(_timer.Dispose);
        }

        public void Stop()
        {
            _cts.Cancel();
        }

        private Timer _timer;
        private readonly CancellationTokenSource _cts;
        private readonly IEnumerable<IProcess> _processes;
    }

    class Program
    {
        static void Main(string[] args)
        {
            var cts = new CancellationTokenSource();
            var token = cts.Token;
            HostFactory.Run(x =>
            {
                x.Service<ProcessRunner>(s =>
                {
                    s.ConstructUsing(name => new ProcessRunner(
                        new List<IProcess>
                        {
                            new Process1(),
                            new Process2()
                        }, token));
                    s.WhenStarted(_ => _.Start());
                    s.WhenStopped(_ => _.Stop());
                });
                x.RunAsLocalSystem();
                // other settings here...
            });
        }
    }
}

以上是关于csharp 定期从Topshelf Windows服务调用多个处理程序(使用System.Threading.Timer)的主要内容,如果未能解决你的问题,请参考以下文章

csharp C#中的Topshelf使用

csharp Topshelf与Windsor的基本用法

csharp 示例Topshelf服务,演示如何使用Fooidity Switchyard切换功能

TopShelf+Quartz.net实现基于window服务的定时调度

csharp Topshelf + OWIN自主机+ ASP.NET WebAPI + Ninject

TopShelf+Quartz.net 实现window服务