/
SafeTimer.cs
47 lines (42 loc) · 1.71 KB
/
SafeTimer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SafeTimer.cs">
// Copyright (c) by respective owners including Yahoo!, Microsoft, and
// individual contributors. All rights reserved. Released under a BSD
// license as described in the file LICENSE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Threading;
using System.Threading.Tasks;
namespace VW.Azure.Trainer
{
internal class SafeTimer
{
private CancellationTokenSource cancellationTokenSource;
private ManualResetEventSlim finishedEvent;
internal SafeTimer(TimeSpan delay, Action action)
{
this.cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
finishedEvent = new ManualResetEventSlim();
Task.Factory
.StartNew(async () =>
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
action();
cancellationToken.ThrowIfCancellationRequested();
await Task.Delay(delay, cancellationToken);
}
},
TaskCreationOptions.LongRunning)
.ContinueWith(t => finishedEvent.Set());
}
public void Stop(TimeSpan timeout)
{
cancellationTokenSource.Cancel();
finishedEvent.Wait(timeout);
}
}
}