code_junkie

Writing code to fire the last method to throw an exception in a multi-threaded web app

Nov 12th, 2011
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. public static class Extensions {
  2. public static void Try(this Action a, int maxTries) {
  3. new (Func<bool>(() => { a(); return true; })).Try(maxTries);
  4. }
  5.  
  6. public static TResult Try<TResult>(this Func<TResult> f, int maxTries) {
  7. Exception lastException = null;
  8.  
  9. for (int i = 0; i < maxTries; i++) {
  10. try {
  11. return f();
  12. } catch (Exception ex) {
  13. lastException = ex;
  14. }
  15. }
  16.  
  17. throw lastException;
  18. }
  19. }
  20.  
  21. // Set a property
  22. new Action(() => myObject.Property = 5).Try(5);
  23.  
  24. // With a return value
  25. var count = new Func<int>(() => myList.Count).Try(3);
  26.  
  27. Utilities.Try(
  28. () => MyObject.Property = 5
  29. ).Repeat(5);
  30.  
  31. Utilities.Try(() => {
  32. MyObject.Property1 = 5;
  33. MyObject.Property2 = 6;
  34. MyObject.Property3 = 7;
  35. }).Repeat(5);
  36.  
  37. public class TryAgain
  38. {
  39. public delegate void CodeToTryAgain ();
  40.  
  41. public static void Repeat<E>(int count, CodeToTryAgain code) where E : Exception
  42. {
  43. while (count-- > 0)
  44. {
  45. try
  46. {
  47. code();
  48. return;
  49. }
  50. catch (E ex)
  51. {
  52. Console.WriteLine("Caught an {0} : {1}", typeof(E).Name, ex.Message);
  53. // ignoring it!
  54. }
  55. }
  56. }
  57. }
  58.  
  59. TryAgain.Repeat<MyException>(5, delegate()
  60. {
  61. ThrowTwice();
  62. });
Add Comment
Please, Sign In to add comment