我正在使用 C#,我想创建一个事件,在填写完 24 小时后向用户显示一个字段。这意味着当该字段被填满时,我必须等待 24 小时才能将其显示给用户。有什么简单的方法吗?我没有写任何代码,是的,因为我在网上找到了建议计时器的示例,它与我的问题不一样。
我正在使用 .NET 3.5
问问题
48 次
2 回答
1
此示例代码(控制台应用程序)演示了何时更改属性值,然后在 24 小时后调用方法来显示数据:
public class Program
{
private CancellationTokenSource tokenSource;
private string _myProperty;
public string MyProperty
{
get
{
return _myProperty;
}
set
{
_myProperty = value;
_ = Run(() => SendToUser(_myProperty), TimeSpan.FromHours(24), tokenSource.Token);
}
}
private static void Main()
{
var prg = new Program();
prg.tokenSource = new CancellationTokenSource();
prg.MyProperty = "Test test";
Console.ReadLine();
}
private void SendToUser(string data)
{
//Display data for user
Console.WriteLine(data);
}
public static async Task Run(Action action, TimeSpan period, CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
await Task.Delay(period, cancellationToken);
if (!cancellationToken.IsCancellationRequested)
action();
}
}
public static Task Run(Action action, TimeSpan period)
{
return Run(action, period, CancellationToken.None);
}
}
于 2021-07-14T04:35:04.297 回答
0
在 .NET 3.5 中:
public class Program
{
private string _myProperty;
public string MyProperty
{
get
{
return _myProperty;
}
set
{
_myProperty = value;
ExecuteAfter(() => SendToUser(_myProperty), TimeSpan.FromHours(24));
}
}
private static void Main()
{
var prg = new Program();
prg.MyProperty = "Test test";
Console.ReadLine();
}
private void SendToUser(string data)
{
//Display data for user
Console.WriteLine(data);
}
public static void ExecuteAfter(Action action, TimeSpan delay)
{
Timer timer = null;
timer = new System.Threading.Timer(s =>
{
action();
timer.Dispose();
}, null, (long)delay.TotalMilliseconds, Timeout.Infinite);
}
}
或使用FluentScheduler - 准备好 nuget 任务调度程序包,https: //www.nuget.org/packages/FluentScheduler/3.1.46
于 2021-07-14T05:47:12.203 回答