9 changed files with 135 additions and 12 deletions
@ -0,0 +1,70 @@ |
|||
using System; |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
|
|||
namespace BBWY.Common.Trigger |
|||
{ |
|||
/// <summary>
|
|||
/// 延迟触发组件
|
|||
/// </summary>
|
|||
public class DelayTrigger |
|||
{ |
|||
public DelayTrigger(int delayTime = 1000) |
|||
{ |
|||
if (delayTime < 1000) |
|||
delayTime = 1000; |
|||
this.delayTime = delayTime; |
|||
} |
|||
/// <summary>
|
|||
/// 延迟执行时间(ms)
|
|||
/// </summary>
|
|||
private int delayTime; |
|||
|
|||
/// <summary>
|
|||
/// 关键字
|
|||
/// </summary>
|
|||
private string currentKey; |
|||
|
|||
/// <summary>
|
|||
/// 是否可以执行
|
|||
/// </summary>
|
|||
private volatile bool canExecute; |
|||
|
|||
/// <summary>
|
|||
/// 是否正在延迟响应中
|
|||
/// </summary>
|
|||
private volatile bool isDelaying; |
|||
|
|||
|
|||
public Action<string> OnExecute; |
|||
|
|||
|
|||
public void SetKey(string key) |
|||
{ |
|||
currentKey = key; |
|||
if (isDelaying) |
|||
{ |
|||
canExecute = false; |
|||
return; |
|||
} |
|||
Task.Factory.StartNew(delegate |
|||
{ |
|||
isDelaying = true; |
|||
while (true) |
|||
{ |
|||
canExecute = true; |
|||
Thread.Sleep(delayTime); |
|||
if (canExecute) |
|||
{ |
|||
Console.ForegroundColor = ConsoleColor.Red; |
|||
Console.WriteLine($"DelayTrigger {currentKey} Execute at {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")}"); |
|||
Console.ResetColor(); |
|||
OnExecute?.Invoke(currentKey); |
|||
isDelaying = false; |
|||
break; |
|||
} |
|||
} |
|||
}); |
|||
} |
|||
} |
|||
} |
Loading…
Reference in new issue