-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEasyTimer.cs
More file actions
88 lines (74 loc) · 2.5 KB
/
Copy pathEasyTimer.cs
File metadata and controls
88 lines (74 loc) · 2.5 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Socket.IO.NET35
{
public class EasyTimer
{
private CancellationTokenSource _ts;
public EasyTimer(CancellationTokenSource ts)
{
this._ts = ts;
}
public static EasyTimer SetTimeout(Action method, int delayInMilliseconds)
{
var ts = new CancellationTokenSource();
var ct = ts.Token;
var worker = new BackgroundWorker();
worker.DoWork += (s, e) => {
//System.Threading.Thread.Sleep(delayInMilliseconds);
if (worker.CancellationPending == false)
{
if (delayInMilliseconds > 0)
{
var cancelled = ct.WaitHandle.WaitOne(delayInMilliseconds);
if (cancelled)
{
return;
}
}
}
else
{
return;
}
};
worker.RunWorkerCompleted += (s, e) =>
{
if (!ts.IsCancellationRequested && !worker.CancellationPending)
{
//Task.Factory.StartNew(method, ct, TaskCreationOptions.AttachedToParent, TaskScheduler.Current).Wait();
if (method != null)
method.Invoke();
}
};
worker.RunWorkerAsync();
// Returns a stop handle which can be used for stopping
// the timer, if required
// The static SetTimeOut returns an instance with the new ts in the constructor
// The caller can then call EasyTimer.Stop
return new EasyTimer(ts);
}
public void Stop()
{
//var log = LogManager.GetLogger(Global.CallerName());
//log.Info("EasyTimer stop");
if (_ts != null)
{
_ts.Cancel();
}
}
//public static void TaskRun(Action action)
//{
// Task.Factory.StartNew(action).Wait();
//}
public static Task TaskRunNoWait(Action action)
{
return Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.AttachedToParent, TaskScheduler.Current);
}
}
}