2018-03-13 14:54:15 +08:00
|
|
|
|
/**
|
|
|
|
|
* Author: Roger Lipscombe
|
|
|
|
|
* Source: https://stackoverflow.com/a/7472334
|
|
|
|
|
* */
|
|
|
|
|
using System;
|
|
|
|
|
using System.Threading;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace BililiveRecorder.Core
|
|
|
|
|
{
|
2018-03-31 14:14:00 +08:00
|
|
|
|
public static class Repeat
|
2018-03-13 14:54:15 +08:00
|
|
|
|
{
|
|
|
|
|
public static Task Interval(
|
|
|
|
|
TimeSpan pollInterval,
|
|
|
|
|
Action action,
|
|
|
|
|
CancellationToken token)
|
|
|
|
|
{
|
|
|
|
|
// We don't use Observable.Interval:
|
|
|
|
|
// If we block, the values start bunching up behind each other.
|
|
|
|
|
return Task.Factory.StartNew(
|
|
|
|
|
() =>
|
|
|
|
|
{
|
|
|
|
|
for (; ; )
|
|
|
|
|
{
|
2018-03-21 20:56:56 +08:00
|
|
|
|
action();
|
2018-03-13 14:54:15 +08:00
|
|
|
|
if (token.WaitCancellationRequested(pollInterval))
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}, token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static class CancellationTokenExtensions
|
|
|
|
|
{
|
|
|
|
|
public static bool WaitCancellationRequested(
|
|
|
|
|
this CancellationToken token,
|
|
|
|
|
TimeSpan timeout)
|
|
|
|
|
{
|
|
|
|
|
return token.WaitHandle.WaitOne(timeout);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|