5

ここで async/await パターンを使用して定期的な作業を行うための優れた方法を見つけました: https://stackoverflow.com/a/14297203/899260

今私がやりたいことは、私ができるように拡張メソッドを作成することです

someInstruction.DoPeriodic(TimeSpan.FromSeconds(5));

それはまったく可能ですか?

編集:

ここまでは、上記のURLのコードを拡張メソッドにリファクタリングしたのですが、そこから先の進め方がわかりません

  public static class ExtensionMethods {
    public static async Task<T> DoPeriodic<T>(this Task<T> task, CancellationToken token, TimeSpan dueTime, TimeSpan interval) {
        // Initial wait time before we begin the periodic loop.
        if (dueTime > TimeSpan.Zero)
            await Task.Delay(dueTime, token);

        // Repeat this loop until cancelled.
        while (!token.IsCancellationRequested) {


            // Wait to repeat again.
            if (interval > TimeSpan.Zero)
                await Task.Delay(interval, token);
        }
    }
}
4

1 に答える 1

4

「定期的な作業」コードはsomeInstructionパブリック メンバーのいずれかにアクセスしていますか? そうでなければ、そもそも拡張メソッドを使用する意味がありません。

someInstructionもしそうなら、それが のインスタンスであると仮定するとSomeClass、次のようなことができます:

public static class SomeClassExtensions
{
    public static async Task DoPeriodicWorkAsync(
                                       this SomeClass someInstruction,
                                       TimeSpan dueTime, 
                                       TimeSpan interval, 
                                       CancellationToken token)
    {
        //Create and return the task here
    }
}

もちろんsomeInstructionTaskコンストラクターにパラメーターとして渡す必要があります (それを可能にするコンストラクターのオーバーロードがあります)。

OPによるコメントに基づく更新:

任意のコードを定期的に実行するための再利用可能なメソッドが必要なだけの場合、拡張メソッドは必要なものではなく、単純なユーティリティ クラスです。あなたが提供したリンクからコードを適応させると、次のようになります。

public static class PeriodicRunner
{
public static async Task DoPeriodicWorkAsync(
                                Action workToPerform,
                                TimeSpan dueTime, 
                                TimeSpan interval, 
                                CancellationToken token)
{
  // Initial wait time before we begin the periodic loop.
  if(dueTime > TimeSpan.Zero)
    await Task.Delay(dueTime, token);

  // Repeat this loop until cancelled.
  while(!token.IsCancellationRequested)
  {
    workToPerform();

    // Wait to repeat again.
    if(interval > TimeSpan.Zero)
      await Task.Delay(interval, token);       
  }
}
}

次に、次のように使用します。

PeriodicRunner.DoPeriodicWorkAsync(MethodToRun, dueTime, interval, token);

void MethodToRun()
{
    //Code to run goes here
}

または単純なラムダ式を使用:

PeriodicRunner.DoPeriodicWorkAsync(() => { /*Put the code to run here */},
   dueTime, interval, token);
于 2013-03-18T07:53:40.190 に答える