Skip to content

Instantly share code, notes, and snippets.

@kkbruce
Created June 1, 2017 05:27
Show Gist options
  • Select an option

  • Save kkbruce/994f3f8488a305701115f2ffbd1009b5 to your computer and use it in GitHub Desktop.

Select an option

Save kkbruce/994f3f8488a305701115f2ffbd1009b5 to your computer and use it in GitHub Desktop.
How to retry in C#
TimeSpan nextDelay = TimeSpan.FromSeconds(2);
int retryNumber = 5;
// 監控結果
string testString = "";
for (int i = 0; i != retryNumber; i++)
{
if (string.IsNullOrWhiteSpace(testString))
{
Console.WriteLine($"String is null, retry {i + 1} ...");
}
else
{
nextDelay = TimeSpan.FromSeconds(0);
}
// 這是非同步,所以不會有執行緒 lock 問題(重點)
await Task.Delay(nextDelay).ConfigureAwait(false);
// 由於是 retry, 希望每次是上一次的 2 倍時間
nextDelay = nextDelay + nextDelay;
// Test
if (i == 2)
{
testString = "Not null :-)";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment