Created
May 15, 2015 11:43
-
-
Save alex-groshev/1e047950cb9b2d12c212 to your computer and use it in GitHub Desktop.
Invoking multiple handlers periodically from Topshelf Windows Service (using System.Threading.Timer)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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