我想运行一个Task,其“heartbeat”会在特定时间间隔内继续运行,直到任务完成。
我认为这样的扩展方法效果很好:
public static async Task WithHeartbeat(this Task primaryTask, TimeSpan heartbeatInterval, Action<CancellationToken> heartbeatAction, CancellationToken cancellationToken)
例如:
public class Program {
public static void Main() {
var cancelTokenSource = new CancellationTokenSource();
var cancelToken = cancelTokenSource.Token;
var longRunningTask = Task.Factory.StartNew(SomeLongRunningTask, cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Current);
var withHeartbeatTask = longRunningTask.WithHeartbeat(TimeSpan.FromSeconds(1), PerformHeartbeat, cancelToken);
withHeartbeatTask.Wait();
Console.WriteLine("Long running task completed!");
Console.ReadLine()
}
private static void SomeLongRunningTask() {
Console.WriteLine("Starting long task");
Thread.Sleep(TimeSpan.FromSeconds(9.5));
}
private static int _heartbeatCount = 0;
private static void PerformHeartbeat(CancellationToken cancellationToken) {
Console.WriteLine("Heartbeat {0}", ++_heartbeatCount);
}
}
该程序应输出:
Starting long task
Heartbeat 1
Heartbeat 2
Heartbeat 3
Heartbeat 4
Heartbeat 5
Heartbeat 6
Heartbeat 7
Heartbeat 8
Heartbeat 9
Long running task completed!
请注意,不应(在正常情况下)输出“Heartbeat 10”,因为心跳在初始超时(即1秒)后开始。同样,如果任务花费的时间少于心跳间隔,则根本不应发生心跳。
实施此方法的好方法是什么?
背景信息:我有一个正在侦听Azure Service Bus队列的服务。在完成处理之前,我不希望Complete消息(将永久删除它从队列中删除),这可能需要比5分钟的最大消息LockDuration更长的时间。因此,我需要使用此心跳方法在锁定持续时间到期之前调用RenewLockAsync,以便在进行冗长处理时消息不会超时。
答案 0 :(得分:13)
这是我的尝试:
public static class TaskExtensions {
/// <summary>
/// Issues the <paramref name="heartbeatAction"/> once every <paramref name="heartbeatInterval"/> while <paramref name="primaryTask"/> is running.
/// </summary>
public static async Task WithHeartbeat(this Task primaryTask, TimeSpan heartbeatInterval, Action<CancellationToken> heartbeatAction, CancellationToken cancellationToken) {
if (cancellationToken.IsCancellationRequested) {
return;
}
var stopHeartbeatSource = new CancellationTokenSource();
cancellationToken.Register(stopHeartbeatSource.Cancel);
await Task.WhenAny(primaryTask, PerformHeartbeats(heartbeatInterval, heartbeatAction, stopHeartbeatSource.Token));
stopHeartbeatSource.Cancel();
}
private static async Task PerformHeartbeats(TimeSpan interval, Action<CancellationToken> heartbeatAction, CancellationToken cancellationToken) {
while (!cancellationToken.IsCancellationRequested) {
try {
await Task.Delay(interval, cancellationToken);
if (!cancellationToken.IsCancellationRequested) {
heartbeatAction(cancellationToken);
}
}
catch (TaskCanceledException tce) {
if (tce.CancellationToken == cancellationToken) {
// Totally expected
break;
}
throw;
}
}
}
}
或稍微调整一下,您甚至可以像以下一样使心跳异步:
/// <summary>
/// Awaits a fresh Task created by the <paramref name="heartbeatTaskFactory"/> once every <paramref name="heartbeatInterval"/> while <paramref name="primaryTask"/> is running.
/// </summary>
public static async Task WithHeartbeat(this Task primaryTask, TimeSpan heartbeatInterval, Func<CancellationToken, Task> heartbeatTaskFactory, CancellationToken cancellationToken) {
if (cancellationToken.IsCancellationRequested) {
return;
}
var stopHeartbeatSource = new CancellationTokenSource();
cancellationToken.Register(stopHeartbeatSource.Cancel);
await Task.WhenAll(primaryTask, PerformHeartbeats(heartbeatInterval, heartbeatTaskFactory, stopHeartbeatSource.Token));
if (!stopHeartbeatSource.IsCancellationRequested) {
stopHeartbeatSource.Cancel();
}
}
public static Task WithHeartbeat(this Task primaryTask, TimeSpan heartbeatInterval, Func<CancellationToken, Task> heartbeatTaskFactory) {
return WithHeartbeat(primaryTask, heartbeatInterval, heartbeatTaskFactory, CancellationToken.None);
}
private static async Task PerformHeartbeats(TimeSpan interval, Func<CancellationToken, Task> heartbeatTaskFactory, CancellationToken cancellationToken) {
while (!cancellationToken.IsCancellationRequested) {
try {
await Task.Delay(interval, cancellationToken);
if (!cancellationToken.IsCancellationRequested) {
await heartbeatTaskFactory(cancellationToken);
}
}
catch (TaskCanceledException tce) {
if (tce.CancellationToken == cancellationToken) {
// Totally expected
break;
}
throw;
}
}
}
允许您将示例代码更改为以下内容:
private static async Task PerformHeartbeat(CancellationToken cancellationToken) {
Console.WriteLine("Starting heartbeat {0}", ++_heartbeatCount);
await Task.Delay(1000, cancellationToken);
Console.WriteLine("Finishing heartbeat {0}", _heartbeatCount);
}
可以使用RenewLockAsync之类的异步调用替换PerformHeartbeat,这样您就不必使用Action方法需要的阻塞调用(如RenewLock)来浪费线程时间。
我answering my own question per SO guidelines,但我也愿意采用更优雅的方法解决这个问题。
答案 1 :(得分:0)
这是我的方法
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Start Main");
StartTest().Wait();
Console.ReadLine();
Console.WriteLine("Complete Main");
}
static async Task StartTest()
{
var cts = new CancellationTokenSource();
// ***Use ToArray to execute the query and start the download tasks.
Task<bool>[] tasks = new Task<bool>[2];
tasks[0] = LongRunningTask("", 20, cts.Token);
tasks[1] = Heartbeat("", 1, cts.Token);
// ***Call WhenAny and then await the result. The task that finishes
// first is assigned to firstFinishedTask.
Task<bool> firstFinishedTask = await Task.WhenAny(tasks);
Console.WriteLine("first task Finished.");
// ***Cancel the rest of the downloads. You just want the first one.
cts.Cancel();
// ***Await the first completed task and display the results.
// Run the program several times to demonstrate that different
// websites can finish first.
var isCompleted = await firstFinishedTask;
Console.WriteLine("isCompleted: {0}", isCompleted);
}
private static async Task<bool> LongRunningTask(string id, int sleep, CancellationToken ct)
{
Console.WriteLine("Starting long task");
await Task.Delay(TimeSpan.FromSeconds(sleep));
Console.WriteLine("Completed long task");
return true;
}
private static async Task<bool> Heartbeat(string id, int sleep, CancellationToken ct)
{
while(!ct.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(sleep));
Console.WriteLine("Heartbeat Task Sleep: {0} Second", sleep);
}
return true;
}
}
}