TransactionScope async await async 事物

Posted codedreams

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TransactionScope async await async 事物相关的知识,希望对你有一定的参考价值。

上菜

async await 机制 确实便捷开发   多线程时 如何一致性如何保证呢?

public async Task<ActionResult<IEnumerable<string>>>  Get()
        {
            using (var trans = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    Console.WriteLine("1:id----" + Thread.CurrentThread.ManagedThreadId.ToString());
                    await TaskAsync("my001");
                    Console.WriteLine("2:id----" + Thread.CurrentThread.ManagedThreadId.ToString());
                    await TaskAsync("my002my002my002my002my002my002my002my002my002my002my002my002my002my002my002my002my002my002my002my002my002my002my002");
                    Console.WriteLine("3:id----" + Thread.CurrentThread.ManagedThreadId.ToString());
                    trans.Complete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("wowo-- ex:" + ex.ToString());
                }

               
            }

            return new string[] { "value1", "value2" };
        }
public async Task TaskAsync(string name)
        {
            using (var db = new SqlConnection("Data Source=.;Initial Catalog=qyy;Uid=sa;Pwd=123456;"))
            {
                Console.WriteLine("4:id-- " + name + "--" + Thread.CurrentThread.ManagedThreadId.ToString());
                await db.OpenAsync();
                await db.ExecuteAsync($@"
                                INSERT INTO [dbo].[a]
                                       ([name])
                                 VALUES
                                       (‘{name}‘)
                        ");
                Console.WriteLine("5:id-- " + name + "--" + Thread.CurrentThread.ManagedThreadId.ToString());
            }
        }

 注:name 字段 varchar(50) 

好了 事物妥妥的执行 未出现任何 异常数据

以上是关于TransactionScope async await async 事物的主要内容,如果未能解决你的问题,请参考以下文章

TransactionScope不能与linux上的async / await方法一起使用

如何在 .NET 4.0 中使用 Microsoft.Bcl.Async 支持 TransactionScope 中的异步方法? [复制]

TransactionScope 事务 = new TransactionScope() VS TransactionScope s = context.Connection.BeginTransac

为啥 TransactionScope 不能与 Sqlite 一起使用?

如何加入 TransactionScope?

TransactionScope 是如何工作的?