Skip to content

Instantly share code, notes, and snippets.

@peitschie
Last active July 13, 2017 00:57
Show Gist options
  • Save peitschie/56b95a33cf5822cb598271ddbe54f183 to your computer and use it in GitHub Desktop.
Save peitschie/56b95a33cf5822cb598271ddbe54f183 to your computer and use it in GitHub Desktop.
Minimal .NET core Windows service using PeterKottas.DotNetCore
using PeterKottas.DotNetCore.WindowsService;
using PeterKottas.DotNetCore.WindowsService.Interfaces;
using System;
using System.IO;
using System.Threading.Tasks;
namespace NetCoreWindowsService
{
class Program
{
static void Main(string[] args)
{
ServiceRunner<Service>.Run(config =>
{
var name = config.GetDefaultName();
config.Service(serviceConfig =>
{
serviceConfig.ServiceFactory((extraArguments) =>
{
return new Service();
});
serviceConfig.OnStart((service, extraArguments) =>
{
Console.WriteLine("Service {0} started", name);
service.Start();
});
serviceConfig.OnStop(service =>
{
Console.WriteLine("Service {0} stopped", name);
service.Stop();
});
serviceConfig.OnError(e =>
{
Console.WriteLine("Service {0} errored with exception : {1}", name, e.Message);
});
});
});
Console.WriteLine("Main exited");
}
}
class Service : IMicroService
{
private Task _service;
private bool _shutdown;
public void Start()
{
_shutdown = false;
_service = Task.Run(ProcessThread);
}
public void Stop()
{
_shutdown = true;
_service.GetAwaiter().GetResult();
}
private async Task ProcessThread()
{
while (_shutdown == false)
{
Console.WriteLine(DateTime.Now);
File.AppendAllLines(@"C:\myservice.txt", new[] { DateTime.Now.ToString() });
await Task.Delay(1000);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment