What is the best way to implement Retry Wrapper in C #?

Currently, we have a naive RetryWrapper that repeats the given function when an exception occurs:

public T Repeat<T, TException>(Func<T> work, TimeSpan retryInterval, int maxExecutionCount = 3) where TException : Exception
{ 
   ... 

And for retryInterval, we use the following logic to β€œwait” before the next attempt.

_stopwatch.Start();
while (_stopwatch.Elapsed <= retryInterval)
{
  // do nothing but actuallky it does! lots of CPU usage specially if retryInterval is high
}
_stopwatch.Reset();

I do not really like this logic, and ideally I would prefer the repetition logic NOT to happen in the main thread, can you come up with a better way?

Note. I will gladly review the answers to .Net> = 3.5

+4
source share
3 answers

T, , . , reset:

Thread.Sleep(retryInterval);

API, , . , async:

public async Task<T> RepeatAsync<T, TException>(Func<T> work, TimeSpan retryInterval, int maxExecutionCount = 3) where TException : Exception
{
     for (var i = 0; i < maxExecutionCount; ++i)
     {
        try { return work(); }
        catch (TException ex)
        {
            // allow the program to continue in this case
        }
        // this will use a system timer under the hood, so no thread is consumed while
        // waiting
        await Task.Delay(retryInterval);
     }
}

:

RepeatAsync<T, TException>(work, retryInterval).Result;

, :

var task = RepeatAsync<T, TException>(work, retryInterval);

// do other work here

// later, if you need the result, just do
var result = task.Result;
// or, if the current method is async:
var result = await task;

// alternatively, you could just schedule some code to run asynchronously
// when the task finishes:
task.ContinueWith(t => {
    if (t.IsFaulted) { /* log t.Exception */ }
    else { /* success case */ }
});
+3

Microsoft Enterprise Library , . - - , . , , , , .

NuGet.

using Microsoft.Practices.TransientFaultHandling;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling;
...
// Define your retry strategy: retry 5 times, starting 1 second apart
// and adding 2 seconds to the interval each retry.
var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), 
  TimeSpan.FromSeconds(2));

// Define your retry policy using the retry strategy and the Windows Azure storage
// transient fault detection strategy.
var retryPolicy =
  new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy);

// Receive notifications about retries.
retryPolicy.Retrying += (sender, args) =>
    {
        // Log details of the retry.
        var msg = String.Format("Retry - Count:{0}, Delay:{1}, Exception:{2}",
            args.CurrentRetryCount, args.Delay, args.LastException);
        Trace.WriteLine(msg, "Information");
    };

try
{
  // Do some work that may result in a transient fault.
  retryPolicy.ExecuteAction(
    () =>
    {
        // Your method goes here!
    });
}
catch (Exception)
{
  // All the retries failed.
}
+2

?

:

    TimeSpan retryInterval = new TimeSpan(0, 0, 5);
    DateTime startTime;
    DateTime retryTime;
    Timer checkInterval = new Timer();

    private void waitMethod()
    {
        checkInterval.Interval = 1000;
        checkInterval.Tick += checkInterval_Tick;         
        startTime = DateTime.Now;
        retryTime = startTime + retryInterval;
        checkInterval.Start();
    }

    void checkInterval_Tick(object sender, EventArgs e)
    {
        if (DateTime.Now >= retryTime)
        {
            checkInterval.Stop();

            // Retry Interval Elapsed
        }   
    }
0

Source: https://habr.com/ru/post/1533325/


All Articles