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

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

    For me this sounds like 'Distributed Transactions', since you have different resources (database, service communication, file i/o) and want to make a transaction that possible involves all of them.

    In C# you could solve this with Microsoft Distributed Transaction Coordinator. For every resource you need a resource manager. For databases, like sql server and file i/o, it is already available, as far as i know. For others you can develop your own.

    As an example, to execute these transactions you can use the TransactionScope class like this:

    using (TransactionScope ts = new TransactionScope())
    {
        //all db code here
    
        // if an error occurs jump out of the using block and it will dispose and rollback
    
        ts.Complete();
    }
    

    (Example taken from here)

    To develop your own resource manager, you have to implement IEnlistmentNotification and that can be a fairly complex task. Here is a short example.

提交回复
热议问题