2013-03-18 57 views
5

我發現瞭如何使用異步/ 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); 
     } 
    } 
} 
+0

你知道如何創建一個擴展方法嗎?如果是的話,你有答案,如果沒有,你可以使用谷歌。 – 2013-03-18 07:37:51

+0

@MarcinJuraszek我將鏈接中的代碼重構爲擴展方法,但我不知道如何從那裏繼續。看我的編輯。 – lightxx 2013-03-18 07:50:20

+0

顯示您的代碼,然後 – MarcinJuraszek 2013-03-18 07:50:52

回答

4

繼續進行,在「週期工作「代碼訪問任何someInstruction公衆成員?如果不是,首先使用擴展方法沒什麼意義。

如果這樣做,並假設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 
    } 
} 

當然,你必須通過someInstructionTask構造函數的參數(有一個構造函數重載,允許你這樣做)。

UPDATE由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); 
+0

hm。我的意圖是這樣的:我將代碼全部重複使用,並且只有評論「// TODO:在這裏做某種工作」。所以我認爲不是將代碼複製並粘貼到所有地方,我想要一些樣板代碼並只傳遞說明。因此,用擴展方法的想法。 – lightxx 2013-03-18 08:00:04

+1

在這種情況下,請參閱更新的答案。 – Konamiman 2013-03-18 08:11:47

+0

謝謝!! btw「公共靜態任務DoPeriodicWorkAsync」應該是「公共靜態異步任務DoPeriodicWorkAsync」;) – lightxx 2013-03-18 08:24:17