Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gtechsltn/7f783b614e9b31e7e19c11e2121d4606 to your computer and use it in GitHub Desktop.
Save gtechsltn/7f783b614e9b31e7e19c11e2121d4606 to your computer and use it in GitHub Desktop.
Invoking multiple handlers periodically from Topshelf Windows Service (using 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...
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment