SqlConnection支持多少个并发语句

How many concurrent statements does SqlConnection support

C# SqlConnection 支持多少个并发语句?

假设我正在处理 Windows 服务 运行 10 个线程。所有线程都使用相同的 SqlConnection 对象但不同的 SqlCommand 对象,并在不同的 table 或相同的 table 上执行 select、插入、更新和删除等操作但不同的数据。它会工作吗?单个 SqlConnection 对象是否能够同时处理 10 个语句?

How many concurrent statements does C# SqlConnection support?

从技术上讲,您可以有多个 "in-flight" 语句,但实际上只有一个在执行。

单个 SqlConnection 映射到 SQL 服务器中的单个 Connection 和 Session。在 Sql 服务器中,会话一次只能有一个 request 活动。如果启用 MultipeActiveResultsets,则可以在前一个查询完成之前开始一个新查询,但语句是交错的,永远不会 运行 并行。

MARS enables the interleaved execution of multiple requests within a single connection. That is, it allows a batch to run, and within its execution, it allows other requests to execute. Note, however, that MARS is defined in terms of interleaving, not in terms of parallel execution.

execution can only be switched at well defined points.

https://docs.microsoft.com/en-us/sql/relational-databases/native-client/features/using-multiple-active-result-sets-mars?view=sql-server-ver15

所以你甚至不能保证另一个语句会 运行 每当一个语句被阻塞时。所以如果要运行语句并行,需要使用多个SqlConnections.

另请注意,单个查询可能使用并行执行计划,并有多个 tasks 运行 并行执行。

David Browne 为您提供了问题的答案,但您可能还需要了解其他信息:

Let's say I am working on Windows service running 10 threads. All threads use the same SqlConnection object but different SqlCommand object and perform operations like select, insert, update and delete on either different tables or same table but different data.

这个设计在几个方面似乎是错误的:

  1. 您保留并打开一次性资源。我对一次性物品的规则是:"Create. Use. Dispose. All in the same piece of code, ideally using a using block." 将一次性物品留在身边,甚至在线程之间共享它,不值得冒着忘记关闭它的危险。

没有性能优势:SqlConnection 使用内部连接池,没有任何副作用。即使有 is a relevant speed advantage,他们也不值得冒险。

  1. 您正在使用带数据库访问的多线程。多线程是实现多任务处理的一种方法,但在需要时不应该使用它。多线程仅对 CPU 绑定工作有用。否则你通常应该使用 async/await 或类似的方法。数据库操作受磁盘或网络限制。

这条规则有一个例外,那就是如果您的应用程序是服务器。服务器是 pleasingly parallel 的罕见例子。因此,拥有一个大型线程池来并行处理传入请求是很常见的。但是,您 编写 其中之一是相当罕见的。大多数情况下,您只是 运行 处理该问题的现有服务器基础架构中的代码。

  1. 如果您确实有繁重的 CPU 工作,那么您很可能需要大量休息。检索很多内容,然后在 C# 代码中进行过滤,这是一个非常常见的初学者错误。不要那样做。在Query中做尽可能多的过滤和处理。您将无法超越 DB-Server 的速度,最多只能毫无意义地占用您的网络。