VisualBean
5/29/2017 - 12:56 PM

PollingService.cs

public class PollingService : IPollingService
{
    private CancellationTokenSource cts = new CancellationTokenSource();

    public PollingService(TimeSpan waitAfterSuccessInterval, TimeSpan waitAfterErrorInterval)
    {
        WaitAfterErrorInterval = waitAfterErrorInterval;
        WaitAfterSuccessInterval = waitAfterSuccessInterval;
    }

    public TimeSpan WaitAfterErrorInterval { get; private set; }
    public TimeSpan WaitAfterSuccessInterval { get; private set; }

    public void StartPoll(Action task, Action<Exception> onException)
    {
        var poll = new Task(() => Poll(task, onException), cts.Token, TaskCreationOptions.LongRunning);
        poll.Start();
    }

    public void StopPoll()
    {
        cts.Cancel();
    }

    protected void Poll(Action task, Action<Exception> OnException)
    {
        CancellationToken cancellation = cts.Token;
        TimeSpan interval = TimeSpan.Zero;
        while (!cancellation.WaitHandle.WaitOne(interval))
        {
            try
            {
                task.Invoke();
                if (cancellation.IsCancellationRequested)
                {
                    break;
                }
                interval = WaitAfterSuccessInterval;
            }
            catch (Exception ex)
            {
                if (OnException != null)
                    OnException(ex);
                interval = WaitAfterErrorInterval;
            }
        }
    }
}