run parallel library example await async c# multithreading windows-services task-parallel-library async-await

parallel - task run async c#



La mejor manera de hacer una tarea de bucle en el servicio de Windows (2)

Tengo un método que envía algunos SMS a nuestros clientes que se ven a continuación:

public void ProccessSmsQueue() { SmsDbContext context = new SmsDbContext(); ISmsProvider provider = new ZenviaProvider(); SmsManager manager = new SmsManager(context, provider); try { manager.ProcessQueue(); } catch (Exception ex) { EventLog.WriteEntry(ex.Message, EventLogEntryType.Error); } finally { context.Dispose(); } } protected override void OnStart(string[] args) { Task.Factory.StartNew(DoWork).ContinueWith( ??? ) }

Entonces, tengo algunos problemas:

  1. No sé cuánto tiempo lleva ejecutar el método;

  2. El método puede arrojar excepciones, que quiero escribir en EventLog

  3. Quiero ejecutar este método en bucle, cada 10 minutos, pero solo después de finalizar la última ejecución.

¿Cómo puedo lograr esto? Pensé en usar ContinueWith() , pero todavía tengo preguntas sobre cómo construir toda la lógica.


Debería tener un método asíncrono que acepte un CancellationToken para saber cuándo detenerse, llama a ProccessSmsQueue en un bloque try-catch y utiliza Task.Delay para esperar asíncronamente hasta la próxima vez que necesite ejecutarse:

public async Task DoWorkAsync(CancellationToken token) { while (true) { try { ProccessSmsQueue(); } catch (Exception e) { // Handle exception } await Task.Delay(TimeSpan.FromMinutes(10), token); } }

Puede llamar a este método cuando se inicia su aplicación y Task.Wait la tarea devuelta antes de que se presente para que sepa que se completa y no tiene excepciones:

private Task _proccessSmsQueueTask; private CancellationTokenSource _cancellationTokenSource; protected override void OnStart(string[] args) { _cancellationTokenSource = new CancellationTokenSource(); _proccessSmsQueueTask = Task.Run(() => DoWorkAsync(_cancellationTokenSource.Token)); } protected override void OnStop() { _cancellationTokenSource.Cancel(); try { _proccessSmsQueueTask.Wait(); } catch (Exception e) { // handle exeption } }


Ejemplo de clase de trabajador que he usado en servicios de Windows. Admite detenerse de una manera "limpia" mediante el uso de un candado. Solo tiene que agregar su código en DoWork, configurar su temporizador en el método StartTimerAndWork (en milisegundos) y usar esta clase en su servicio.

public class TempWorker { private System.Timers.Timer _timer = new System.Timers.Timer(); private Thread _thread = null; private object _workerStopRequestedLock = new object(); private bool _workerStopRequested = false; private object _loopInProgressLock = new object(); private bool _loopInProgress = false; bool LoopInProgress { get { bool rez = true; lock (_loopInProgressLock) rez = _loopInProgress; return rez; } set { lock (_loopInProgressLock) _loopInProgress = value; } } #region constructors public TempWorker() { } #endregion #region public methods public void StartWorker() { lock (_workerStopRequestedLock) { this._workerStopRequested = false; } _thread = new Thread(new ThreadStart(StartTimerAndWork)); _thread.Start(); } public void StopWorker() { if (this._thread == null) return; lock (_workerStopRequestedLock) this._workerStopRequested = true; int iter = 0; while (LoopInProgress) { Thread.Sleep(100); iter++; if (iter == 60) { _thread.Abort(); } } //if (!_thread.Join(60000)) // _thread.Abort(); } #endregion #region private methods private void StartTimerAndWork() { this._timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); this._timer.Interval = 10000;//milliseconds this._timer.Enabled = true; this._timer.Start(); } #endregion #region event handlers private void timer_Elapsed(object sender, ElapsedEventArgs e) { if (!LoopInProgress) { lock (_workerStopRequestedLock) { if (this._workerStopRequested) { this._timer.Stop(); return; } } DoWork(); } } private void DoWork() { try { this.LoopInProgress = true; //DO WORK HERE } catch (Exception ex) { //LOG EXCEPTION HERE } finally { this.LoopInProgress = false; } } #endregion }