Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class Extensions {
- public static void Try(this Action a, int maxTries) {
- new (Func<bool>(() => { a(); return true; })).Try(maxTries);
- }
- public static TResult Try<TResult>(this Func<TResult> f, int maxTries) {
- Exception lastException = null;
- for (int i = 0; i < maxTries; i++) {
- try {
- return f();
- } catch (Exception ex) {
- lastException = ex;
- }
- }
- throw lastException;
- }
- }
- // Set a property
- new Action(() => myObject.Property = 5).Try(5);
- // With a return value
- var count = new Func<int>(() => myList.Count).Try(3);
- Utilities.Try(
- () => MyObject.Property = 5
- ).Repeat(5);
- Utilities.Try(() => {
- MyObject.Property1 = 5;
- MyObject.Property2 = 6;
- MyObject.Property3 = 7;
- }).Repeat(5);
- public class TryAgain
- {
- public delegate void CodeToTryAgain ();
- public static void Repeat<E>(int count, CodeToTryAgain code) where E : Exception
- {
- while (count-- > 0)
- {
- try
- {
- code();
- return;
- }
- catch (E ex)
- {
- Console.WriteLine("Caught an {0} : {1}", typeof(E).Name, ex.Message);
- // ignoring it!
- }
- }
- }
- }
- TryAgain.Repeat<MyException>(5, delegate()
- {
- ThrowTwice();
- });
Add Comment
Please, Sign In to add comment