You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
1.8 KiB
70 lines
1.8 KiB
using System;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace QYMessageCenter.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;
|
|
}
|
|
}
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|