You could write a RepeatActionEvery()
method as follows.
It's parameters are:
action
- The action you want to repeat every so often.
interval
- The delay interval between calling action()
.
cancellationToken
- A token you use to cancel the loop.
Here's a compilable console application that demonstrates how you can call it. For an ASP application you would call it from an appropriate place.
Note that you need a way to cancel the loop, which is why I pass a CancellationToken
to RepeatActionEvery()
. In this sample, I use a cancellation source which automatically cancels after 8 seconds. You would probably have to provide a cancellation source for which some other code called .Cancel()
at the appropriate time. See here for more details.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
sealed class Program
{
void run()
{
CancellationTokenSource cancellation = new CancellationTokenSource(
TimeSpan.FromSeconds(8));
Console.WriteLine("Starting action loop.");
RepeatActionEvery(() => Console.WriteLine("Action"),
TimeSpan.FromSeconds(1), cancellation.Token).Wait();
Console.WriteLine("Finished action loop.");
}
public static async Task RepeatActionEvery(Action action,
TimeSpan interval, CancellationToken cancellationToken)
{
while (true)
{
action();
Task task = Task.Delay(interval, cancellationToken);
try
{
await task;
}
catch (TaskCanceledException)
{
return;
}
}
}
static void Main(string[] args)
{
new Program().run();
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…