Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading.Tasks;
- using Polly;
- namespace AsyncDelegateGotcha
- {
- public class Program
- {
- static async Task Main(string[] args)
- {
- var toTestSync = new PollySyncAsyncTest();
- var toTestAsync = new PollySyncAsyncTest();
- await toTestSync.TestSync();
- await toTestAsync.TestAsync();
- Console.ReadLine();
- }
- }
- class PollySyncAsyncTest
- {
- private int _counter = 0;
- public async Task TestAsync()
- {
- var policy = Policy
- .Handle<Exception>()
- .RetryAsync(3);
- await policy.ExecuteAsync(async () =>
- {
- var something = await DoSomethingAsync();
- if (something != true) throw new Exception("Assert fail");
- });
- }
- public async Task TestSync()
- {
- var policy = Policy
- .Handle<Exception>()
- .Retry(3);
- await policy.Execute( // Executing a Func<Task> delegate through a sync policy.
- async () => // Providing the compiler an async delegate where it expects a sync delegate.
- {
- var something = await DoSomethingAsync();
- if (something != true) throw new Exception("Assert fail");
- });
- }
- private async Task<bool> DoSomethingAsync()
- {
- await Task.Delay(TimeSpan.FromSeconds(1));
- if (++_counter <= 2) throw new Exception("Fault which we might expect the policy to handle");
- return true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement