14

タスクが完了するまで特定の時間間隔で実行し続ける「ハートビート」を持つタスクを実行したいと思います。

このような拡張メソッドがうまくいくと思います:

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!

ハートビートは最初のタイムアウト (つまり 1 秒) 後に開始されるため、(通常の状況では) "Heartbeat 10" を出力しないことに注意してください。同様に、タスクにかかる時間がハートビート間隔より短い場合、ハートビートはまったく発生しません。

これを実装する良い方法は何ですか?

背景情報: Azure Service Busキューをリッスンするサービスがあります。処理が完了するまでメッセージを完了させたくありません(キューから完全に削除されます)。これには、メッセージの最大LockDurationである 5 分よりも長い時間がかかる可能性があります。したがって、このハートビート アプローチを使用して、ロック期間が終了する前にRenewLockAsyncを呼び出す必要があります。これにより、長時間の処理が行われている間にメッセージがタイムアウトにならなくなります。

4

2 に答える 2

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);
}

PerformHeartbeat はRenewLockAsyncのような非同期呼び出しに置き換えることができるため、Action アプローチで必要になるRenewLockのようなブロッキング呼び出しを使用してスレッド時間を無駄にする必要はありません。

私はSO ガイドライン に従って自分の質問に答えていますが、この問題に対するよりエレガントなアプローチにもオープンです。

于 2013-06-14T18:52:10.287 に答える
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;
    }

}

}

于 2016-08-02T01:31:22.923 に答える