C# - Quickie- How can I make changes to the Repeat Action file so it tests the e
ID: 3775449 • Letter: C
Question
C# - Quickie- How can I make changes to the Repeat Action file so it tests the exception type. Modify the program to include this, and use delegates instead of defined functions for both the Action and the exception test when calling the method. The reapat action source code is below.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace RepeatActionDemo_01
{
class Program
{
static void Main(string[] args)
{
RepeatAction(UpdateFile, 8, 10);
Console.Write("Done.");
Console.ReadKey();
}
public static void UpdateFile()
{
File.AppendAllText(@"c: empdata01.txt", " Last updated: " +
DateTime.Now.ToShortTimeString() + " ");
}
public static void RepeatAction(Action action, int maxTimeout, int maxTries)
{
int tries = 0;
bool repeat = true;
int sleepSeconds = 1;
do
{
try
{
action();
repeat = false;
}
catch (Exception ex)
{
if (tries++ > maxTries)
throw new Exception("Too many retries.", ex);
Console.WriteLine("Exception hit " + DateTime.Now.ToShortTimeString());
Thread.Sleep(TimeSpan.FromSeconds(sleepSeconds));
sleepSeconds *= 2;
if (sleepSeconds > maxTimeout)
sleepSeconds = 1;
}
}
while (repeat);
}
}
}
Explanation / Answer
public static class Retry
{
public static void Do(
Action action,
TimeSpan retryInterval,
int retryCount = 3)
{
Do<object>(() =>
{
action();
return null;
}, retryInterval, retryCount);
}
public static T Do<T>(
Func<T> action,
TimeSpan retryInterval,
int retryCount = 3)
{
var exceptions = new List<Exception>();
for (int retry = 0; retry < retryCount; retry++)
{
try
{
if (retry > 0)
Thread.Sleep(retryInterval);
return action();
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
throw new AggregateException(exceptions);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.