Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. using System;
  2. using System.Threading.Tasks;
  3. using Polly;
  4.  
  5. namespace AsyncDelegateGotcha
  6. {
  7. public class Program
  8. {
  9. static async Task Main(string[] args)
  10. {
  11. var toTestSync = new PollySyncAsyncTest();
  12. var toTestAsync = new PollySyncAsyncTest();
  13.  
  14. await toTestSync.TestSync();
  15. await toTestAsync.TestAsync();
  16.  
  17. Console.ReadLine();
  18. }
  19. }
  20.  
  21. class PollySyncAsyncTest
  22. {
  23. private int _counter = 0;
  24.  
  25. public async Task TestAsync()
  26. {
  27. var policy = Policy
  28. .Handle<Exception>()
  29. .RetryAsync(3);
  30.  
  31. await policy.ExecuteAsync(async () =>
  32. {
  33. var something = await DoSomethingAsync();
  34. if (something != true) throw new Exception("Assert fail");
  35. });
  36. }
  37.  
  38. public async Task TestSync()
  39. {
  40. var policy = Policy
  41. .Handle<Exception>()
  42. .Retry(3);
  43.  
  44. await policy.Execute( // Executing a Func<Task> delegate through a sync policy.
  45. async () => // Providing the compiler an async delegate where it expects a sync delegate.
  46. {
  47. var something = await DoSomethingAsync();
  48. if (something != true) throw new Exception("Assert fail");
  49. });
  50. }
  51.  
  52. private async Task<bool> DoSomethingAsync()
  53. {
  54. await Task.Delay(TimeSpan.FromSeconds(1));
  55.  
  56. if (++_counter <= 2) throw new Exception("Fault which we might expect the policy to handle");
  57.  
  58. return true;
  59. }
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement