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

后端 未结 5 887
后悔当初
后悔当初 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:53

    Well...sounds like a really, really nasty situation. You can't open a transaction, write something to the database and go walk your dog in the park. Because transactions have this nasty habit of locking resources for everyone. This eliminates your best option: distributed transactions.

    I would execute all operations and prepare a reverse script as I go. If operation is a success I would purge the script. Otherwise I would run it. But this is open for potential pitfalls and script must be ready to handle them. For example - what if in the mid-time someone already updated the records you added; or calculated an aggregate based on your values?

    Still: building a reverse script is the simple solution, no rocket science there. Just

    List reverseScript;
    

    and then, if you need to rollback:

    using (TransactionScope tx= new TransactionScope()) {
        foreach(Command cmd in reverseScript) cmd.Execute();
        tx.Complete();
    }
    

提交回复
热议问题