SqlConnection 是否并行处理查询? [英] Does SqlConnection processes queries in parallel?

查看:29
本文介绍了SqlConnection 是否并行处理查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我打开一个 SqlConnection 到 SQL Server,然后从多个后台线程发出多个查询,所有查询都使用那个连接 - 这些查询是否会按顺序执行(不关心顺序)?

具体来说,如果在一个查询开始时更改隔离级别,然后在该查询结束时恢复它 - 此隔离级别是否有可能适用于其他查询?

我想不是,但想确认一下.

SQL Server 2008 R2

我说的是System.Data.SqlClient.SqlConnection

解决方案

已加载的问题,不可能有明确的答案,因为正如@LasseV.Karlsen 所说,SqlConnection 不是线程安全的,因此行为将是不可预测的.我过去尝试过类似的场景并失败了.这是我认为使用您问题中的参数会发生的情况.

<块引用>

SqlConnection 是否并行处理查询?

不,它不知道怎么做,因为它不是为这个任务设计的.尽管可以构建以这种方式使用它的流程这一事实很诱人.

<块引用>

这些查询会按顺序执行吗

是的.SQL 引擎将按照收到的顺序执行查询.尽管您的连接对象可能不知道将结果传递回哪个线程,但您会遇到可怕的对象引用错误".

<块引用>

此隔离级别是否有可能适用于其他查询

是的.如果您更改分配给 SqlConnection 的事务对象的隔离级别,然后您的一个线程尝试使用该连接,则默认情况下它将具有该隔离级别.此时,辅助线程执行此操作的时间是您无法控制的.您可以为每个命令分配一个事务(从而根据需要获得唯一的隔离级别),但您仍然会遇到连接不是线程安全的问题.>

If I open a SqlConnection to a SQL Server, and then issue multiple queries from multiple background threads, all using that one connection - will those queries be executed sequentially (don't care about the order)?

Specifically, if at the beginning of one query I change isolation level and then restore it at the end of that query - is there a chance that this isolation level may apply to other queries?

I think not, but want to confirm.

SQL Server 2008 R2

And I am talking about System.Data.SqlClient.SqlConnection

解决方案

Loaded question, a definitive answer is impossible because as @LasseV.Karlsen has stated SqlConnection is not thread safe so behavior is going to be unpredictable. I attempted similar scenarios in the past and failed. Here is what I think will happen with the parameters in your question.

Does SqlConnection processes queries in parallel?

No, it does not know how because it wasn't designed for this task. Though the fact that it's possible to build a process to use it in this manner is tempting.

will those queries be executed sequentially

Yes. The queries will be executed by the SQL engine in the order received. Though your connection object will probably not know which thread to pass results back to and you'll get the dreaded 'object reference error'.

is there a chance that this isolation level may apply to other queries

Yes. If you change the isolation level of the transaction object assigned to your SqlConnection and then one of your threads attempts to use that connection it will have that isolation level by default. The timing of when a secondary thread will do this is out of your control at this point. You can assign a transaction per command (and thereby attain a unique isolation level as desired) but you'll still have the issue of the connection not being thread safe.

这篇关于SqlConnection 是否并行处理查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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