2 {
3 private readonly int _timeout;
4 private readonly DateTime _enqueueTime;
5
6 public bool IsTimeout
7 {
8 get { return (DateTime.Now - _enqueueTime).TotalSeconds > _timeout; }
9 }
10 public string Key { get; private set; }
11 public Action Continue { get; private set; }
12
13 public LazyItem(string key, int timeout, Action continueAction)
14 {
15 _enqueueTime = DateTime.Now;
16 _timeout = timeout;
17 Key = key;
18 Continue = continueAction;
19 }
20 }
{
public string Name
{
get { return "Lazy Invoke Task"; }
}
public bool IsRunning { get; private set; }
private readonly ConcurrentDictionary<string, LazyItem> _lazyActions = new ConcurrentDictionary<string, LazyItem>();
public void Start()
{
Task.Factory.StartNew(Run);
IsRunning = true;
}
public void Stop()
{
IsRunning = false;
}
/// <summary>
/// 检测被延迟的任务,达到超时时间则触发
/// </summary>
/// Created by:marvin(2014/10/11 12:14)
public void Run()
{
while (IsRunning)
{
if (_lazyActions.Count > 0)
{
var removeKeys = (from lazyItem in _lazyActions where lazyItem.Value.IsTimeout select lazyItem.Key).ToList();
if (removeKeys.Count > 0)
{
foreach (var key in removeKeys)
{
LazyItem tmp;
if (_lazyActions.TryRemove(key, out tmp))
{
tmp.Continue();
}
}
}
}
Thread.Sleep(1 * 1000);
}
}
/// <summary>
/// 延迟工作
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="lazyTimeout">The lazy timeout.</param>
/// <param name="continueAction">The continue action.</param>
/// Created by:marvin(2014/10/11 11:48)
public void LazyDo(string id, int lazyTimeout, Action continueAction)
{
if (!_lazyActions.ContainsKey(id))
{
if (_lazyActions.TryAdd(id, new LazyItem(id, lazyTimeout, continueAction)))
{
Console.WriteLine("lazy action : {0} , timeout : {1}", id, lazyTimeout);
}
}
}
/// <summary>
/// 取消任务
/// </summary>
/// <param name="actionKey">The action key.</param>
/// Created by:marvin(2014/10/11 12:02)
public void Cancel(string actionKey)
{
if (_lazyActions.ContainsKey(actionKey))
{
LazyItem tmp;
if (_lazyActions.TryRemove(actionKey, out tmp))
{
Console.WriteLine("lazy action “{0}” had removed", tmp.Key);
}
}
}
}
2 {
3 static void Main(string[] args)
4 {
5 var lazyInvoker = new LazyInvoker();
6 lazyInvoker.Start();
7
8 //延迟7秒运行
9 lazyInvoker.LazyDo(Guid.NewGuid().ToString(), 7, DoSomething);
10 Thread.Sleep(5 * 1000);
11
12 //延迟3秒运行,但是3秒的时候被取消
13 var id = Guid.NewGuid().ToString();
14 lazyInvoker.LazyDo(id, 5, DoSomething);
15 Thread.Sleep(3 * 1000);
16 lazyInvoker.Cancel(id);
17
18 Console.ReadKey();
19 }
20
21 private static void DoSomething()
22 {
23 Console.WriteLine("Now time is :" + DateTime.Now.ToString("HH:mm:ss"));
24 }
25 }