是否可以异步提交/回滚SqlTransaction? [英] Is it possible to commit/rollback SqlTransaction in asynchronous?

查看:74
本文介绍了是否可以异步提交/回滚SqlTransaction?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以异步方式提交/回滚 SqlTransaction .但是看起来不支持异步.有什么方法可以使它异步而无需使用原始SQL来启动事务?

I'm trying to commit/rollback SqlTransaction in asynchronous. But it look like asynchronous is not supported. Is there any way to make it asynchronous without using raw SQL to start transaction?

推荐答案

它看起来不像.通过相关代码,所有其他方法都是异步的(同步版本是特例),而 SqlTransaction 和其他相关代码仅是同步的.对于重叠的部分, SqlTransaction 只需同步地等待任务完成(例如,在处理重新连接时).

It doesn't look like it. Going through the relevant code, all the other methods are asynchronous through and through (the synchronous version is the special case), while SqlTransaction and the other relevant code is synchronous only. For the parts that overlap, the SqlTransaction simply synchronously waits for task completion (e.g. when handling reconnects).

实际上,当您深入研究代码时,事务操作明确禁止任何异步操作,因此不包括异步事务操作似乎是设计使然.如果确实找到了解决方法,请记住这一点-该系统并非设计为允许并发操作,因此始终总是使用 await 来获得(无论如何)任务回来.

In fact, as you get through the depths of the code, the transaction operations explicitly forbid any asynchronous operations, so not including asynchronous transaction operations seems to be by design. If you do find a workaround, keep this in mind - the system is not designed to allow concurrent operations, so always use await as soon as you get the (whatever) task back.

如果要解决此问题,则必须一直深入到直接为SQL Server创建二进制消息(或至少使用反射来执行一些内部帮助器方法),这是没有用的太简单了(当然,这将要求您访问 SqlConnection 使用的内部TCP连接-并处理重新连接等.)

If you wanted to go around this, you'd have to dig all the way down to creating the binary messages for SQL Server directly (or at least using reflection to execute some of the internal helper methods), which is not going to be all too easy (and it would require you to get access to the internal TCP connection used by SqlConnection, of course - and handle the reconnects etc.).

查看EntityFramework代码,他们的解决方案非常简单-他们只需调用 Commit .这并不像听起来那样疯狂-首当其冲的工作是在 ExecuteXXXAsync 方法本身中完成的, Commit 是免费的"-只需花费您与服务器通信,通常不太昂贵.

Looking at EntityFramework code, their solution is pretty simple - they just call Commit. This isn't as crazy as it might sound - the brunt of the work is done in the ExecuteXXXAsync methods themselves, the Commit is "free" - it only costs you the communication with the server, which usually isn't too expensive.

鉴于这些限制,您的性能仍然不会受到显着影响-如果您有几个并发的 Commit ,则您的线程池可能必须分配比通常数量多一两个线程,但是替代方案要痛苦得多.

Given those limitations, your performance still shouldn't be affected noticeably - your thread pool might have to allocate a thread or two over the usual amount if you've got a few concurrent Commits, but the alternative is much more painful.

这篇关于是否可以异步提交/回滚SqlTransaction?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆