Which is the best way to add a retry/rollback mechanism for sync/async tasks in C#?

后端 未结 5 949
后悔当初
后悔当初 2021-02-04 01:15

Imagine of a WebForms application where there is a main method named CreateAll(). I can describe the process of the method tasks step by step as follows:

1) Stores to da

5条回答
  •  自闭症患者
    2021-02-04 01:56

    Look at using Polly for retry scenarios which seems to align well with your Pseudo code. At the end of this answer is a sample from the documentation. You can do all sorts of retry scenarios, retry and waits etc. For example, you could retry a complete transaction a number of times, or alternatively retry a set of idempotent actions a number of times and then write compensation logic if/when the retry policy finally fails.

    A memento patterns is more for undo-redo logic that you would find in a word processor (Ctrl-Z and Ctrl-Y).

    Other helpful patterns to look at is a simple queue, a persistent queue or even a service bus to give you eventual consistency without having to have the user wait for everything to complete successfully.

    // Retry three times, calling an action on each retry 
    // with the current exception and retry count
    Policy
        .Handle()
        .Retry(3, (exception, retryCount) =>
        {
            // do something 
        });
    

    A sample based on your Pseudo-Code may look as follows:

    static bool CreateAll(object1 obj1, object2 obj2)
    {
         // Policy to retry 3 times, waiting 5 seconds between retries.
         var policy =
             Policy
                  .Handle()
                  .WaitAndRetry(3, count =>
                  {
                     return TimeSpan.FromSeconds(5); 
                  });
    
           policy.Execute(() => UpdateDatabase1(obj1));
           policy.Execute(() => UpdateDatabase2(obj2));
      }
    

提交回复
热议问题