我在这里找到了一种使用异步/等待模式进行定期工作的好方法: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);
        }
    }
}

最佳答案

“定期工作”代码是否访问任何someInstruction公共(public)成员?如果不是,那么首先使用扩展方法就没有多大意义。

如果是这样,并假设someInstructionSomeClass的实例,则可以执行以下操作:

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

当然,您必须将someInstruction作为参数传递给Task构造函数(存在构造函数重载,您可以执行此操作)。

根据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
}

或使用简单的lambda表达式:
PeriodicRunner.DoPeriodicWorkAsync(() => { /*Put the code to run here */},
   dueTime, interval, token);

关于c# - 创建扩展方法以进行定期工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15471708/

10-12 12:44
查看更多