上菜
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)
好了 事物妥妥的执行 未出现任何 异常数据
原文地址:https://www.cnblogs.com/codedreams/p/9299148.html
时间: 2024-10-09 17:28:10