Files
Umbraco-CMS/src/Umbraco.Web/Scheduling/DelayedRecurringTaskBase.cs

75 lines
2.0 KiB
C#
Raw Normal View History

2015-02-06 16:10:34 +01:00
using System;
using System.Threading;
using System.Threading.Tasks;
2015-02-06 16:10:34 +01:00
namespace Umbraco.Web.Scheduling
{
/// <summary>
/// Provides a base class for recurring background tasks.
/// </summary>
/// <typeparam name="T">The type of the managed tasks.</typeparam>
internal abstract class DelayedRecurringTaskBase<T> : RecurringTaskBase<T>, ILatchedBackgroundTask
2015-02-06 16:10:34 +01:00
where T : class, IBackgroundTask
{
private readonly ManualResetEventSlim _latch;
2015-02-06 16:10:34 +01:00
private Timer _timer;
protected DelayedRecurringTaskBase(IBackgroundTaskRunner<T> runner, int delayMilliseconds, int periodMilliseconds)
: base(runner, periodMilliseconds)
{
if (delayMilliseconds > 0)
{
_latch = new ManualResetEventSlim(false);
_timer = new Timer(_ =>
{
_timer.Dispose();
_timer = null;
_latch.Set();
});
_timer.Change(delayMilliseconds, 0);
}
2015-02-06 16:10:34 +01:00
}
protected DelayedRecurringTaskBase(DelayedRecurringTaskBase<T> source)
: base(source)
{
// no latch on recurring instances
_latch = null;
2015-02-06 16:10:34 +01:00
}
public override void Run()
2015-02-06 16:10:34 +01:00
{
if (_latch != null)
_latch.Dispose();
base.Run();
}
2015-02-17 15:09:29 +01:00
public override async Task RunAsync(CancellationToken token)
{
if (_latch != null)
_latch.Dispose();
2015-02-17 15:09:29 +01:00
await base.RunAsync(token);
}
public WaitHandle Latch
{
get
{
if (_latch == null)
throw new InvalidOperationException("The task is not latched.");
return _latch.WaitHandle;
2015-02-06 16:10:34 +01:00
}
}
public bool IsLatched
{
get { return _latch != null; }
}
public virtual bool RunsOnShutdown
2015-02-06 16:10:34 +01:00
{
get { return true; }
2015-02-06 16:10:34 +01:00
}
}
}