I am using C# and I want to create an event that display a field to the user after 24 hours after it is been filled up. Meaning when the field is filled up I have to wait 24 hours before I display it to the user.
Is there any simple way to do so?
I didn't write any code yes since examples I found on line where suggesting timers and it doesn't resemble my problem.
I'm using .NET 3.5
Asked
Active
Viewed 112 times
2

Mindan
- 979
- 6
- 17
- 37
-
Timer examples you have found online should allow for a 24-hour tick time. – Eric J. Jul 14 '21 at 03:34
2 Answers
1
This sample code (Console application) demonstrates when property value changed, then after 24 hour calls method to showing data:
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);
}
}

Wai Ha Lee
- 8,598
- 83
- 57
- 92

Mansur Kurtov
- 726
- 1
- 4
- 12
-
I voted for you answer, but unfortuntly it won't apply in my case as I'm on .NET 3.5 which does not support the CancellationTokenSource – Mindan Jul 14 '21 at 05:35
-
@Mindan in your question not any information about .net versions? – Mansur Kurtov Jul 14 '21 at 05:36
-
I understand and apology for any inconvenient, I edited the question with mention of the .NET version – Mindan Jul 14 '21 at 05:39
0
In .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);
}
}
or use FluentScheduler - ready nuget task scheduler package, https://www.nuget.org/packages/FluentScheduler/3.1.46

Wai Ha Lee
- 8,598
- 83
- 57
- 92

Mansur Kurtov
- 726
- 1
- 4
- 12