Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static class Program
- {
- static void Main()
- {
- ServiceBase[] ServicesToRun;
- ServicesToRun = new ServiceBase[]
- {
- new MyService()
- };
- ServiceBase.Run(ServicesToRun);
- }
- }
- public partial class MyService : ServiceBase
- {
- private bool IsRunning;
- private static string ConnectionString
- {
- get
- {
- return ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
- }
- }
- public MyService()
- {
- InitializeComponent();
- }
- protected override void OnStart(string[] args)
- {
- this.IsRunning = true;
- this.Agendar();
- }
- protected override void OnStop()
- {
- this.IsRunning = false;
- }
- private void Agendar()
- {
- if (!this.IsRunning)
- return;
- var processo = Task.Run(Processar);
- processo.ContinueWith(task =>
- {
- Console.WriteLine(task.Exception);
- }, TaskContinuationOptions.OnlyOnFaulted);
- }
- private async Task Reagendar()
- {
- await Task.Delay(TimeSpan.FromMinutes(5));
- this.Agendar();
- }
- private async Task Processar()
- {
- try
- {
- using (var conexao = new SqlConnection(MyService.ConnectionString))
- {
- await conexao.OpenAsync();
- using (var comando = new SqlCommand(Properties.Resources.MyQueryName, conexao))
- {
- var sqlDepedency = new SqlDependency(comando);
- sqlDepedency.OnChange += (sender, e) =>
- {
- this.Agendar();
- };
- (await comando.ExecuteReaderAsync()).Close();
- }
- }
- }
- catch (Exception err)
- {
- Task.Run(Reagendar);
- Console.WriteLine(task.Exception);
- return;
- }
- this.DoSomeWork();
- }
- private async Task DoSomeWork()
- {
- using (var contexto = new MyDbContext())
- {
- // regras de negocio.
- }
- }
- }
- (await comando.ExecuteReaderAsync()).Close();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement