Я написал это на днях.
public static void Retry(Action fileAction, int iteration)
{
try
{
fileAction.Invoke();
}
catch (IOException)
{
if (interation < MaxRetries)
{
System.Threading.Thread.Sleep(IterationThrottleMS);
Retry(fileAction, ++iteration);
}
else
{
throw;
}
}
}
Вы должны будете объявить MaxRetries
и IterationThrottleMS
самостоятельно или, возможно, сделать их параметрами.
РЕДАКТИРОВАТЬ Я приведу пример.Как я признаю, это было бы излишним, если бы его не использовали повторно
//A little prep
const int IterationThrottleMS = 1000;
const int MaxRetries = 5;
public static void Retry(Action fileAction)
{
Retry(fileAction, 1)
}
...
// Your first example
try
{
Retry(() => {
using (FileStream Fs = new FileStream(
fileName,
FileMode.Open,
FileAccess.Write)
StreamReader stream = new StreamReader(Fs);
});
}
catch (FileNotFoundException) {/*Somthing Sensible*/}
catch (ArgumentException) {/*Somthing Sensible*/}
catch (IOException) {/*Somthing Sensible*/}
...
// Your second example
try
{
Retry(() => writePermission.Demand());
}
catch (FileNotFoundException) {/*Somthing Sensible*/}
catch (ArgumentException) {/*Somthing Sensible*/}
catch (IOException) {/*Somthing Sensible*/}