Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. static class Program
  2. {
  3. static void Main()
  4. {
  5. ServiceBase[] ServicesToRun;
  6. ServicesToRun = new ServiceBase[]
  7. {
  8. new MyService()
  9. };
  10. ServiceBase.Run(ServicesToRun);
  11. }
  12. }
  13.  
  14.  
  15. public partial class MyService : ServiceBase
  16. {
  17. private bool IsRunning;
  18.  
  19. private static string ConnectionString
  20. {
  21. get
  22. {
  23. return ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
  24. }
  25. }
  26.  
  27. public MyService()
  28. {
  29. InitializeComponent();
  30. }
  31.  
  32. protected override void OnStart(string[] args)
  33. {
  34. this.IsRunning = true;
  35. this.Agendar();
  36. }
  37.  
  38. protected override void OnStop()
  39. {
  40. this.IsRunning = false;
  41. }
  42.  
  43. private void Agendar()
  44. {
  45. if (!this.IsRunning)
  46. return;
  47. var processo = Task.Run(Processar);
  48. processo.ContinueWith(task =>
  49. {
  50. Console.WriteLine(task.Exception);
  51. }, TaskContinuationOptions.OnlyOnFaulted);
  52. }
  53.  
  54. private async Task Reagendar()
  55. {
  56. await Task.Delay(TimeSpan.FromMinutes(5));
  57. this.Agendar();
  58. }
  59.  
  60. private async Task Processar()
  61. {
  62. try
  63. {
  64. using (var conexao = new SqlConnection(MyService.ConnectionString))
  65. {
  66. await conexao.OpenAsync();
  67. using (var comando = new SqlCommand(Properties.Resources.MyQueryName, conexao))
  68. {
  69. var sqlDepedency = new SqlDependency(comando);
  70. sqlDepedency.OnChange += (sender, e) =>
  71. {
  72. this.Agendar();
  73. };
  74.  
  75. (await comando.ExecuteReaderAsync()).Close();
  76. }
  77. }
  78. }
  79. catch (Exception err)
  80. {
  81. Task.Run(Reagendar);
  82. Console.WriteLine(task.Exception);
  83. return;
  84. }
  85.  
  86. this.DoSomeWork();
  87. }
  88.  
  89. private async Task DoSomeWork()
  90. {
  91. using (var contexto = new MyDbContext())
  92. {
  93. // regras de negocio.
  94. }
  95. }
  96. }
  97.  
  98. (await comando.ExecuteReaderAsync()).Close();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement