CSharp · Console
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace WatchLoop
{
public class Program
{
static public void Main(string[] args)
{
var cancellationSource = new CancellationTokenSource();
WatchExeTime2(InformAboutLongTime, cancellationSource.Token);
Console.WriteLine("Going to execute a long time operation.");
Thread.Sleep(1600);
cancellationSource.Cancel();
Console.WriteLine("The long time operation executed");
}
static private void InformAboutLongTime()
{
Console.WriteLine("The operation in progress, please wait");
}
static private void WatchExeTime(Action action, CancellationToken cancellationToken)
{
Task.Run(
() =>
{
var sw = new Stopwatch();
sw.Start();
var invokeAt = TimeSpan.FromMilliseconds(200);
while (true)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
if (sw.Elapsed > invokeAt)
{
action();
sw.Restart();
}
}
},
cancellationToken).ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);
}
private static void WatchExeTime2(Action action, CancellationToken cancellationToken)
{
Task.Run(
() =>
{
var waitFor = TimeSpan.FromMilliseconds(200);
while (cancellationToken.IsCancellationRequested == false)
{
var cancelled = cancellationToken.WaitHandle.WaitOne(waitFor);
if (cancelled)
{
break;
}
action();
}
},
cancellationToken).ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);
}
}
}